John Jiang
John Jiang

Reputation: 11509

Python rounding issue

I have come across a very strange issue in python. (Using python 2.4.x)

In windows:

>>> a = 2292.5
>>> print '%.0f' % a
2293

But in Solaris:

>>> a = 2292.5
>>> print '%.0f' % a
2292

But this is the same in both windows and solaris:

>>> a = 1.5
>>> print '%.0f' % a
2

Can someone explain this behavior? I'm guessing it's platform dependent on the way that python was compiled?

Upvotes: 10

Views: 1942

Answers (3)

jh45dev
jh45dev

Reputation: 177

round() rounds toward the nearest even integer
"%n.nf" works the same way as round()
int() truncates towards zero

"rounding a positive number to the nearest integer
can be implemented by adding 0.5 and truncating"
-- http://en.wikipedia.org/wiki/Rounding

In Python you can do this with: math.trunc( n + 0.5 )
assuming n is positive of course...

Where "round half to even" is not appropriate, i now use
math.trunc( n + 0.5 ) where i used to use int(round(n))

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 882681

The function ultimately in charge of performing that formatting is PyOS_snprintf (see the sources). As you surmise, that's unfortunately system-dependent, i.e., it relies on vsprintf, vsnprintf or other similar functions that are ultimately supplied by the platform's C runtime library (I don't recall if the C standard says anything about the '%f' formatting for floats that are "exactly midway" between two possible rounded values... but, whether the C standard is lax about this, or rather the C standard is strict but some C runtimes break it, ultimately is a pretty academic issue...).

Upvotes: 10

Flávio Amieiro
Flávio Amieiro

Reputation: 44316

I is plataform dependent. You can find the documentation here.

It is good to user ceil or floor when you know what you want (to round up or down).

Upvotes: 0

Related Questions