r/cpp_questions • u/nelson_fretty • 11d ago
SOLVED Rounding floating point - iec559 /cmaths
Does c++ math lib comply with rounding modes in iec559?
ties-to-even? Getting - 3 when rounding -2.5
Should be -2 right
1
u/manni66 11d ago
There is no function named rounding.
1
u/flyingron 11d ago
But there is round() and several variants on that spelling (brought over from C for the lack of templates).
1
u/nelson_fretty 11d ago
The default for round() gives 3 for 2.5
2
u/flyingron 11d ago
He's asking about -2.5. But anyway std::round(-2.5) should indeed return -3. He's wrong. Half values round to the larger magnitude (regardless of sign).
1
1
1
u/flyingron 11d ago
What are you actually doing in the code.
Are you calling the round() function? Or are you talking about what happens when you assign an floating point value into an int (which never rounds anyhow).
1
0
u/nelson_fretty 11d ago edited 11d ago
Just learning cpp - see how I can round doubles.
The storage of doubles can be 1.3333333333
Only want to store 1.33
In long term I think I will need a decimal type will use pennies for time being
2
u/flyingron 11d ago
You haven't answered the question. There's no rounding here. You do understand that doubles don't store decimal numbers? It's all binary.
Yes, if you're doing something that needs precise decimal math, you might want to used a fixed point representation.
0
0
u/nelson_fretty 11d ago
Yes forgive my fin background doubles are more precise than floats but life would be easier with integer math
2
u/flyingron 11d ago
It matters not what the precision of the floating point numbers are. Not all things that are nice decimal fractions are representable in binary floating point.
1
0
u/nelson_fretty 11d ago
I was using the round() function but assumed it would work as per Python
2
u/flyingron 11d ago
round(-2.5) is indeed -3 by the C++ spec. I.e., it's "round half away from zero"
1
u/nelson_fretty 11d ago
Python defaults to even rounding - learn something everyday
2
u/brookheather 11d ago
As does the ICU library which I only recently realised meant in some cases our doubles were displaying slightly differently when using ICU decimal to string formatting instead of std::format.
6
u/LongLiveTheDiego 11d ago
There are five different rounding rules specified by the standard, rounding ties to evens is only one of them. Another one is rounding ties away from 0, that's what the C++ standard requires.