Hi Team,
In C programming, we can avoid printing trailing zeros when a floating-point number is assigned to a float variable. For example:
%g Format Specifier:
- The %g format specifier is a general format specifier that automatically chooses the most compact representation for a floating-point number. It either uses the %f or %e (scientific notation) format depending on the magnitude of the number and the precision requested.
- No trailing zeros: One of the key behaviors of %g is that it removes trailing zeros from the fractional part. For example:
10.000 will be printed as 10
10.500 will be printed as 10.5
10.123 will be printed as 10.123
Currently, we are using a string() function to display the float number in the GUI application. My question is: Without specifying the resolution, how can we print float values without trailing zeros?
Below is my C function that truncates unwanted digits and rounds the number based on the number of digits I pass to the function. However, one issue with this approach is that it adds trailing zeros after cutting off values. Fortunately, using a printf function with the %g specifier can prevent trailing zeros. I would like to achieve the same behavior in my function.
API:
float truncate_float(float value, int decimal_places) {
// Handle edge case where decimal_places is negative
if (decimal_places < 0) {
return value; // return the original value if decimal_places is negative
}
// Step 1: Calculate the scale factor (10^decimal_places)
float scale = pow(10.0f, decimal_places);
// Step 2: Truncate the value by multiplying by scale, flooring, and dividing by scale
float truncated_value = floorf(value * scale) / scale;
// Step 3: If the truncated value is an integer, return it as an integer
if (truncated_value == (int)truncated_value) {
return (int)truncated_value; // Cast to int to remove decimals
}
// Step 4: If it's not an integer, return the truncated value as a float
return truncated_value;
}
Regards,
Ayyappan R