Printing float values with fixed number of decimal places through cout in C Here, we will learn how to print float value with fixed number of decimal places using cout in C program? Cout prints a floating pointer number with a maximum of 6 decimal places (some compilers may print 5 decimal places) by default (without trailing zeros). For representing floating point numbers, we use float, double and long double. What’s the difference? Double has 2x more precision then float. Float is a 32 bit IEEE 754 single precision Floating Point Number1 bit for the sign, (8 bits for the exponent, and 23. for the value), i.e. Float has 7 decimal digits of precision.
C printf The printf function in C is used to write a formatted string to stdout. Printf prototype. Converts floating-point number to either decimal or decimal exponent notation: n: Returns the number of characters written so far by this call to the function. The result is written to the value pointed to by the argument. Decimal 0.7 cannot be represented in binary exactly 2. Type of 0.7 is double, the value is: 0.11b 3.
I have a column of floating point data that I need to right justify and align the decimal points. Help.
Data looks something like this.
30.768
1.345
.430
When in doubt, use the old workhorse printf(). I have played around with manipulators like [php]cout << setfill('0') << setw(8) << d1;
[/php] with results that cause only consternation. The old printf() like Chainsaw mentioned works well:
[php]// right justified numeric output (Dev-C++)
you could, for example, use printf or sprintf or its ilk. Take a look at the specifications for the strings. You can control right or left justification, leading zeros, number of digits after the decimals, etc.
If your output is using a proportional font, the spaces won't be as wide as the digits, so that can be a problem too; hopefully you will use a non-proportional font, or else you'll have to do placement in some measurement like pixels or inches.