How can I round a float value (such as 37.777779) to two decimal places (37.78) in C?
Let me first attempt to justify my reason for adding yet another answer to this question. In an ideal world, rounding is not really a big deal. However, in real systems, you may need to contend with several issues that can result in rounding that may not be what you expect. For example, you may be performing financial calculations where final results are rounded and displayed to users as 2 decimal places; these same values are stored with fixed precision in a database that may include more than 2 decimal places (for various reasons; there is no optimal number of places to keep...depends on specific situations each system must support, e.g. tiny items whose prices are fractions of a penny per unit); and, floating point computations performed on values where the results are plus/minus epsilon. I have been confronting these issues and evolving my own strategy over the years. I won't claim that I have faced every scenario or have the best answer, but below is an example of my approach so far that overcomes these issues:
Suppose 6 decimal places is regarded as sufficient precision for calculations on floats/doubles (an arbitrary decision for the specific application), using the following rounding function/method:
double Round(double x, int p)
{
if (x != 0.0) {
return ((floor((fabs(x)*pow(double(10.0),p))+0.5))/pow(double(10.0),p))*(x/fabs(x));
} else {
return 0.0;
}
}
Rounding to 2 decimal places for presentation of a result can be performed as:
double val;
// ...perform calculations on val
String(Round(Round(Round(val,8),6),2));
For val = 6.825
, result is 6.83
as expected.
For val = 6.824999
, result is 6.82
. Here the assumption is that the calculation resulted in exactly 6.824999
and the 7th decimal place is zero.
For val = 6.8249999
, result is 6.83
. The 7th decimal place being 9
in this case causes the Round(val,6)
function to give the expected result. For this case, there could be any number of trailing 9
s.
For val = 6.824999499999
, result is 6.83
. Rounding to the 8th decimal place as a first step, i.e. Round(val,8)
, takes care of the one nasty case whereby a calculated floating point result calculates to 6.8249995
, but is internally represented as 6.824999499999...
.
Finally, the example from the question...val = 37.777779
results in 37.78
.
This approach could be further generalized as:
double val;
// ...perform calculations on val
String(Round(Round(Round(val,N+2),N),2));
where N is precision to be maintained for all intermediate calculations on floats/doubles. This works on negative values as well. I do not know if this approach is mathematically correct for all possibilities.