What is the correct way to round 331.449999 to 1 decimal place

98 Views Asked by At

Should 331.449999 be 331.4 or 331.5?

I can see a issue with a programming framework I am using. I think I am getting erroneous results in some cases and wanted to make sure I am using the right math results, before I raise a bug for it.

In the framework 331.45 -> 331.5

2

There are 2 best solutions below

0
On

The number $331.449999$ cannot be represented as a $32$-bit floating point, but is stored as $331.45001220703125$, which gets rounded to $331.5$.

0
On

There is no such thing as a “correct” way to round. There are many different ways to round, and to check if the rounding is being done correctly you’d have to specify what kind of rounding you’re asking about.

Rounding to the nearest tenth (a common default way to round) would round that number down. However, there are many mathematical and non-mathematical reasons why the computer might not be doing that.

Notably, your number can’t be represented in 32 bits and the closest 32 bit number is big enough to get rounded the other way. So even if it was trying to round to the nearest tenth, it might not achieve that.