It will print 88.89 to the console because, 88.888 with a hundredths place rounding precision equals 88.89.
How do I make "b" equal to the value of "a" rounded to the hundredths place. (e.g. 88.89)
How do I make it so its like, | float b = "a" rounded to nearest hundredths place etc.
Basically how do I make a float equal to another float, but with lower precision
EXAMPLE:
a = 88.888
b = 88.89
c = 88.9
I don't want it to print to console, I just want these rounded values given to a variable because I require a rounded number in my program, and all the other numbers are 2 decimal places out. It would throw off the program if it was more than the hundredths place (banking software, we don't have a denomination past cents. We just need hundredths place basically).
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
float a = 88.888;
cout << fixed << setprecision(2) << a << endl;
float b;
return 0;
}
How do I make "b" equal to the value of "a" rounded to the hundredths place. (e.g. 88.89)
Depending on the particular target value, you cannot. For example, the number 88.89 is not representable in 32 bit IEEE-754 floating point format, so you simply cannot have a float with that value in that representation.
What you can have instead is a value that is very very close to it, such as 88.8899993896484375. If this is what you want, then it is achievable.
A simple solution is to use the string formatting facilities. The character streams have manipulator called std::setprecision
, as you have shown. Simply convert the float to a string with desired precision, and then convert the string back to float.
Another solution is to use a bit of math. An intuitive and seemingly trivial solution would be:
std::round(a * 100.f) / 100.f;
There is a problem however. When the input value is near the threshold where direction of rounding changes, the lack of floating point precision can cause the input value to be on the wrong side for the purpose of the rounding direction.
For example, the closest representable value to 0.005 is actually 0.004999999888241291046142578125 which rounds down instead of up that we would have hoped from 0.005.
We can work around this by using one more decimal of precision and do an intermediate rounding:
std::round(
std::round(a * 1000.f) / 10.f
) / 100.f;
banking software, we don't have a denomination past cents
I recommend to not use finite precision floating point for banking software. Use integers to represent cents when you don't want more precision. And when you do need more precision, use arbitrary precision arithmetic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With