It is perhaps not entirely clear what you require, but I assume:
float precision( float f, int places )
{
float n = std::pow(10.0f, places ) ;
return std::round(f * n) / n ;
}
Then given:
float a = 8.888 ;
The following:
float b = precision( a, 2 ) ; // 8.89
float c = precision( a, 1 ) ; // 8.9
However be clear that while the mathematical value of b
for example is 8.89 and default standard output methods will print it as such, the stored value will be as near to 8.89 as the binary floating point representation allows. So for example while:
std::cout << a << '\n' ;
std::cout << b << '\n' ;
std::cout << c << '\n' ;
Outputs:
8.888
8.89
8.9
Setting the output precision reveals the limitation of representing decimal real values in binary floating point:
std::cout << std::setprecision(8) ;
std::cout << a << '\n' ;
std::cout << b << '\n' ;
std::cout << c << '\n' ;
outputs:
8.8879995
8.8900003
8.8999996
Which is fine and probably meets your requirements, but you may need to be aware to avoid errors. For example do not expect c == 8.9
to be true
- Expect:
std::cout << ((c == 8.9) ? "equal\n" : "not equal\n") ;
to output not equal
. In my test:
std::cout << ((c == 8.9f) ? "equal\n" : "not equal\n") ;
did outout equal
; but I would not rely on that. In the first instance the converted c
is implicitly converted to double, and in that conversion its value differs form the literal double
8.9.
That of course is a general rule not to compare a floating point value for exact equality. Instead you should:
std::cout << ((c - 8.9f < 0.01f) ? "equal\n" : "not equal\n") ;
For this reason, you would not generally use binary floating point for banking software. You would use decimal floating point. For that you would need library support or a different language. C# (and any .Net supported language) for example has a decimal
type with at least 28 digits of precision.
Financial apps in general should not in any event round to the nearest cent in many cases - share prices and currency exchange rates for example are expressed in fractions of a cent. You would only want to round at the final result.
Suffice it to say that there are issues to resolve beside the simple rounding of the stored value (as opposed to rounding the presentation).