4

I want to display floating point number with fixed width before decimal. So far I managed to do it by taking the integer part, displaying desired width and filling with 0 using "%03d" before number value and then displaying the decimal part. I want to know if there is standard way of displaying like for example "%3.3f". I tried the following

printf("value: %3.3f", value);

But the result was only 1 digit before decimal.

How can I achieve it ?

sujan_014
  • 516
  • 2
  • 8
  • 22

4 Answers4

4

You can use

printf("%07.3f", value);

where 07 means printing at least 7 characters with padding zero.

e.g.

printf("%07.3f", 3.3);

prints

003.300

Serge45
  • 324
  • 2
  • 7
2

You can almost achieve it. printf("value: %M.Nf", value); will display at least M total characters and N digits after the decimal point.

printf("value: %9.3f", -123.4);   --> " -123.400"
printf("value: %9.3f", 12345.0);  --> "12345.000"
printf("value: %9.3f", 123456.0); --> "123456.000"

For 3 before and 3 after, use "%7.3f". Good for values [-99.999 999.999].

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch(), system("pause"), or input loop */

int main(int argc, char *argv[]) {

    printf("%08.3f", -7.193583);
    return 0;
}
Florian Castellane
  • 1,197
  • 2
  • 14
  • 38
  • It is better to avoid code only answers. A little explanation describing how it works and why it solves OP's issue would improve the answer a lot. – Roberto Caboni Feb 05 '22 at 12:31
-1

At the risk of being a strong power consumer, use this format..

double offset = 3.14159;
printf("Offset: %06d.%02d sec", (int)offset, (int)(100*(offset - (int)offset)));
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • 3
    The correct answer has already been provided in this 4-year-old question. This answer is full of problems: `(int)offset` is undefined behavior if the conversion overflows, and the multiplication by 100 can round up and produce `100`, displaying a `double` number such as 3.9999999999999996 as “3.100”. – Pascal Cuoq Jul 22 '19 at 09:00