Issues with set precision

I am writing a program on Mac that compares costs + tax(6.5 %)
I choose something that is $5.00 plus .325 tax. Whenever i use cout<<setprecision(2) to only display 2 decimal places, it still treats the number as 5.325 instead of rounding it to 5.33 like i would like it to.

cout<<fixed<<setprecision(2);
float tax= total_cost * 6.5
float after_tax = total cost + tax;
//it displays 5.32 but whenever i choose to pay 5.32 it says that that is lower than after tax. someone please help

Last edited on
original tax = .325
my desired answer for tax is .33 but instead i get .32. why won't set precision round it
setprecision() affects the way the number is displayed, but it doesn't affect the number itself.

Part of the problem here is that we are viewing the values as decimals, but internally they are stored in binary format.
See for example the binary/decimal/ hex converter here:
https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
If you enter 32.5 in the 'decimal box, the binary converted result is shown:100000.10
In that case the number can be represented exactly in binary.

Now try instead the value 0.325 in the decimal box. The binary conversion is: .010100110011001100110011001100110011001100110011001100110011

That recurring pattern is similar to the decimal representation of say 1/3 which is 0.333333...

Just as some values cannot be represented exactly in decimal, there are some which cannot be represented exactly in binary.

This isn't an easy problem to resolve. One way to begin is by doing the calculations internally using the smallest unit of currency, such as the cent rather than the dollar. This doesn't solve all problems, but is a start.

You could also make use of the std::round function.
http://www.cplusplus.com/reference/cmath/round/
It will round to the nearest whole number. If you want to round to 2 decimal places, there are three steps.
1. multiply the value by 100.
2. round that result.
3. divide the result from step 2 by 100.

Last edited on
Topic archived. No new replies allowed.