How to extract two decimal places in the C language?
In the C language, there are various methods to extract two decimal places.
- Formatting output using the printf function:
float num = 3.14159;
printf("%.2f", num); // 输出结果为 3.14
This method will format floating-point numbers according to the specified format, keeping two decimal places.
- Convert a floating-point number to a string and then truncate it using the sprintf function.
float num = 3.14159;
char str[10];
sprintf(str, "%.2f", num);
printf("%s", str); // 输出结果为 3.14
After converting the floating point number to a string using this method, you can use string manipulation functions to extract the two decimal places.
- Using the floor function and pow function:
#include <math.h>
float num = 3.14159;
float result = floorf(num * 100) / 100;
printf("%.2f", result); // 输出结果为 3.14
This method involves multiplying the floating point number by 100, then using the floor function to round down, and finally dividing by 100 to obtain the value with two decimal places.
- Type conversion using floating-point numbers:
float num = 3.14159;
float result = (int)(num * 100) / 100.0;
printf("%.2f", result); // 输出结果为 3.14
This method involves multiplying the floating-point number by 100, then forcefully converting it into an integer, and finally dividing by 100.0, to obtain the value with two decimal places.
It is important to note that the above methods all involve truncating or converting the floating-point numbers, resulting in either a floating-point number or a character array (string).