Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - round a float to 2 digits

I would need to have a float variable rounded to 2 significant digits and store the result into a new variable (or the same of before, it doesn't matter) but this is what happens:

>>> a    
981.32000000000005    
>>> b= round(a,2)    
>>> b
981.32000000000005

I would need this result, but into a variable that cannot be a string since I need to insert it as a float...

>>> print b    
981.32

Actually truncate would also work I don't need extreme precision in this case.

like image 704
user3484521 Avatar asked Oct 17 '25 08:10

user3484521


1 Answers

What you are trying to do is in fact impossible. That's because 981.32 is not exactly representable as a binary floating point value. The closest double precision binary floating point value is:

981.3200000000000500222085975110530853271484375

I suspect that this may come as something of a shock to you. If so, then I suggest that you read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

You might choose to tackle your problem in one of the following ways:

  1. Accept that binary floating point numbers cannot represent such values exactly, and continue to use them. Don't do any rounding at all, and keep the full value. When you wish to display the value as text, format it so that only two decimal places are emitted.
  2. Use a data type that can represent your number exactly. That means a decimal rather than binary type. In Python you would use decimal.
like image 107
David Heffernan Avatar answered Oct 19 '25 21:10

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!