Retain two decimal places for output in C language: use the printf() function; specify the format specifier %.2f, which means that floating point numbers retain two decimal places.
Retain two decimal places for output in C language
In C language, use printf()
function formats output, we can control the number of decimal places by specifying the format specifier. For preserving two decimal places, you can use the %.2f
formatting specifier.
Format specifier%.2f
means outputting a floating point number, retaining two decimal places. For example:
<code class="c">#include <stdio.h> int main() { float number = 123.456789; printf("%.2f\n", number); // 输出:123.46 return 0; }</code>
In the above code, the printf()
function uses the %.2f
format specifier to format the output floating point number number
, keep two decimal places. The output result is 123.46
.
It should be noted that the %.2f
format specifier only controls the format of the output and does not change the precision of the floating point number itself. If the floating point number is not precise enough to maintain two decimal places, the output result will be rounded.
The above is the detailed content of How to retain two decimal places for output in C language. For more information, please follow other related articles on the PHP Chinese website!