Quantcast
Viewing all articles
Browse latest Browse all 13

Answer by user648852 for Checking if float is equivalent to an integer value in python

It is hard to argue with standards.

In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.

Assuming the convention is common rounding, this is the same as the C99 convention in Python:

#!/usr/bin/pythonimport mathinfinity = math.ldexp(1.0, 1023) * 2def nearbyint(x): """returns the nearest int as the C99 standard would"""   # handle NaN   if x!=x:       return x         if x >= infinity:       return infinity   if x <= -infinity:       return -infinity   if x==0.0:       return x   return math.floor(x + 0.5)

If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker's Rounding for example.

Once you have decided on the convention, round to an int and compare to the other int.


Viewing all articles
Browse latest Browse all 13

Trending Articles