Home > Article > Backend Development > How to get two decimal places in C language
In C language, the steps to take two decimal places: multiply the floating point number by 100 and move the decimal point two places to the right. Round the result and discard the part after the decimal point. Divide the rounded result by 100 to obtain a floating-point number with two decimal places.
How to use C language to get two decimal places
In C language, you can use the following steps to get the decimal point The last two digits:
Code example:
<code class="c">#include <stdio.h> int main() { float number = 123.456; // 乘以 100,将小数点向右移动两位 int tmp = number * 100; // 取整,舍弃小数点后的部分 int rounded = tmp / 1; // 除以 100,得到保留两位小数的浮点数 float rounded_number = (float)rounded / 100; // 输出结果 printf("原浮点数:%f\n", number); printf("保留两位小数的浮点数:%f\n", rounded_number); return 0; }</code>
Output:
<code>原浮点数:123.456001 保留两位小数的浮点数:123.45</code>
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!