Post by JackI'd like to round some floating point numbers with 2 decimal places
precision. For example 12.5521 => 12.55. I want to discard/truncate the
third and forth and all after that decimal places. Are there any C/C++
libraries that do this? Don't want to roll my own cos too lazy :)
double round(double a, unsigned digits_after)
{
double multiplier = pow(10, digits_after);
return int(a * multiplier + 0.5) / multiplier;
}
(verify how it works with negative numbers, fix if necessary)
Beware, however, that just like with any other arithmetic operations,
you might get a slightly imprecise result. 12.55 cannot be exactly
represented in computers using binary form, so watch out for the values
like 12.5499999999999999.
Perhaps you can explain why you want to round those numbers. If you're
trying to come up with a solution for handling money, then you need to
consult books written about implementing accounting. IIRC, you actually
don't want to use fractions when dealing with money, and instead
represent your amounts in the lowest denomination (cent, pfennig, grosz,
kopeck) and not currency (dollars, mark, zloty, ruble). If you're
trying to create a better output, then using proper format would take
away the need to round the number (RTFM on 'fprintf' or 'ostream').
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask