'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 ?
Solution 1:[1]
You can almost achieve it. printf("value: %M.Nf", value); will display at least M characters and N digits after the decimal point.
printf("value: %9.3f", -123.4); --> " -123.400"
printf("value: %9.3f", 123456.0); --> "123456.000"
Solution 2:[2]
#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;
}
Solution 3:[3]
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)));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chux - Reinstate Monica |
| Solution 2 | Florian Castellane |
| Solution 3 | Roberto Caboni |
