Reputation: 10970
In Python I am using a format string to have comma separator and to round off. But rounding off is not consistent. For example
>>> '{:,.0f}'.format(1.5)
'2' # Here it is increasing to next integer
>>> '{:,.0f}'.format(2.5)
'2' # Here it is suppose to give 3 as per the earlier logic.
It is depending upon the number before the decimal point. If it is even, then Python is rounding off by increasing the integer value, and the other way around for odd numbers.
Can someone help me in getting consistent rounding off for all numbers
Upvotes: 2
Views: 1151
Reputation: 11948
Actually, .format()
is rounding consistently -- just not the way you might expect.
The IEEE floating point standard defines two different ways of rounding to the nearest numbers. You're expecting it to go away from zero:
2.5 rounds to 3.0
1.5 rounds to 2.0
0.5 rounds to 1.0
-0.5 rounds to -1.0
-1.5 rounds to -2.0
THe other way is to round to even numbers:
2.5 rounds to 2.0
1.5 rounds to 2.0
0.5 rounds to 0.0
-0.5 rounds to -0.0 (yes, this is different from 0)
-1.5 rounds to -2.0
This method is unbiased, in the sense that the sum/average of the rounded numbers is more likely to match the sum/average of the original numbers. That's why IEEE recommends this as the default rule for rounding.
The implementation of rounding varies from function to function, version to version. Here's a table of how different expressions round:
x 2.5 1.5 0.5 -0.5 -1.5
round(x) in Py 2.x away 3.0 2.0 1.0 -1.0 -2.0
round(x) in Py 3.x even 2.0 2.0 0.0 -0.0 -2.0 Changed behaviour
'{:.0f}'.format(x) even 2 2 0 -0 -2
'%.0f' % x even 2 2 0 -0 -2
numpy.around(x) even 2.0 2.0 0.0 0.0 -2.0
Also see dawg's answer on how you can choose your own rounding behaviour using the Decimal module. And John La Rooy has answered a similar question
Upvotes: 4
Reputation: 271
The Float number may be a bit vary which unpredictable such as 1.5 might be 1.4999999 or 1.5000001. So you can't expect the same result for .5 sharp values.
In this case, it has many way to solve such as add a small number to it like 0.0001
Upvotes: -1