If, there is a project that you can only use '%.nf', or 'casting' to limit the value. How can you drop(not rounding) after second decimal places?
Asked
Active
Viewed 227 times
-5
-
*How can you drop(not rounding) after second decimal places?* -- Good luck when you are trying to fix that odd case where it doesn't work, and in trying to fix it, you break something else. Just giving you a warning when trying to finagle with floating point data. – PaulMcKenzie Mar 23 '22 at 20:33
-
Are you cropping the number, internally, or do you want to display the number with only 2 digits after the decimal point? – Thomas Matthews Mar 23 '22 at 20:34
-
This recent question seems to be the same: https://stackoverflow.com/q/71557221 – prapin Mar 23 '22 at 20:43
-
1`((int)(x*100))/100.0` - it's more a math question, isn't it? – Thomas Weller Mar 23 '22 at 20:43
-
@ThomasMatthews I want to display with only 2 digits after the dimicial point. – JAC Mar 23 '22 at 20:46
-
@ThomasWeller Oh WOW THANKS!!!!! Thanks so much!!!!!! I LOVE U sweet honey!!!! – JAC Mar 23 '22 at 20:49
-
See `std::set_precision` to control the output format for floating point values. – Thomas Matthews Mar 23 '22 at 20:50
-
@ThomasMatthews `std::setprecision` will round the result. – Remy Lebeau Mar 23 '22 at 23:33
1 Answers
-1
((int)(x*100))/100.0
How does it work?
x*100
moves the 2 digits from behind the decimal point to in front of the decimal point.
(int)
makes the floating point value an integer, dropping all remaining decimal digits.
/100.0
moves the last 2 digits to behind the decimal point, where they were before.
Note that due to the IEEE-754 way of how floating point numbers are stored internally, the actual floating point number may not have exactly 2 digits after the decimal point.

Remy Lebeau
- 555,201
- 31
- 458
- 770

Thomas Weller
- 55,411
- 20
- 125
- 222
-
1@Sebastian: as per OPs question: "drop(not rounding)", so I chose not to round. – Thomas Weller Mar 23 '22 at 22:44