How do I restrict a float value to only two places after the decimal point in C?

How can I round a float value (such as 37.777779) to two decimal places (37.78) in C?


Solution 1:

If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
float nearest = roundf(val * 100) / 100;  /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.

As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.

For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.

Solution 2:

Using %.2f in printf. It only print 2 decimal points.

Example:

printf("%.2f", 37.777779);

Output:

37.77

Solution 3:

Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:

printf("%.2f", 37.777779);

But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.

See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.

Solution 4:

How about this:

float value = 37.777779;
float rounded = ((int)(value * 100 + .5) / 100.0);