The methods to get two decimal places in C language are: use the format string printf("%.2f", number); use the rounding function round(number * 100) / 100; use truncation Function trunc(number * 100) / 100.
How to get two decimal places in C language
In C language, you can get it by the following method Two decimal places:
Use format string
<code class="c">#include <stdio.h> int main() { double number = 123.456789; printf("%.2f\n", number); // 输出:123.46 return 0; }</code>
printf
Format string in function%.2f
specifies the precision of floating point number output to two decimal places.
Using the rounding function
<code class="c">#include <math.h> int main() { double number = 123.456789; number = round(number * 100) / 100; // 舍入到小数点后两位 printf("%.2f\n", number); // 输出:123.46 return 0; }</code>
round
The function rounds a number to the nearest integer. Multiply the number by 100 before rounding to only two decimal places.
Use the truncation function
<code class="c">#include <math.h> int main() { double number = 123.456789; number = trunc(number * 100) / 100; // 截断到小数点后两位 printf("%.2f\n", number); // 输出:123.45 return 0; }</code>
trunc
The function truncates the number and discards the decimal part. Multiply the number by 100 and then truncate it so that only the whole number remains after the decimal point.
The above is the detailed content of How to get two decimal places in C language. For more information, please follow other related articles on the PHP Chinese website!