sujan_014
sujan_014

Reputation: 536

Displaying fixed width floating point number before decimal

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 ?

Upvotes: 5

Views: 5831

Answers (4)

chux
chux

Reputation: 154255

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].

Upvotes: 3

이인환
이인환

Reputation: 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)));

Upvotes: -1

Stephen Kaguri
Stephen Kaguri

Reputation: 61

#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;
}

Upvotes: 1

Serge45
Serge45

Reputation: 334

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

Upvotes: 5

Related Questions