Home > Article > Backend Development > How to keep two decimal places in C language
In C language, to retain two decimal places, you can: declare a floating-point variable. Use the printf() function to print floating point variables. Use the %.2f format specifier in the format string.
How to retain two decimal places in C language
In C language, you can use printf ()
function and specify the decimal digit format to retain two decimal places.
Specific steps:
printf()
function: printf()
function to print floating point variables. printf()
function, use the %.2f
format specifier. This will preserve two decimal places. Sample code:
<code class="c">#include <stdio.h> int main() { float number = 3.14159265; // 浮点型变量 printf("%.2f", number); // 输出保留两位小数 return 0; }</code>
Output:
<code>3.14</code>
In this example, although number
The value of the variable has 9 decimal places, but the printf("%.2f", number)
statement will truncate the output to two decimal places, which is <code>3.14</code>.
The above is the detailed content of How to keep two decimal places in C language. For more information, please follow other related articles on the PHP Chinese website!