Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does str() round up floats?

The built-in Python str() function outputs some weird results when passing in floats with many decimals. This is what happens:

>>> str(19.9999999999999999)
>>> '20.0'

I'm expecting to get:

>>> '19.9999999999999999'

Does anyone know why? and maybe workaround it?

Thanks!

like image 555
Ofir Avatar asked Dec 03 '22 02:12

Ofir


1 Answers

It's not str() that rounds, it's the fact that you're using floats in the first place. Float types are fast, but have limited precision; in other words, they are imprecise by design. This applies to all programming languages. For more details on float quirks, please read "What Every Programmer Should Know About Floating-Point Arithmetic"

If you want to store and operate on precise numbers, use the decimal module:

>>> from decimal import Decimal
>>> str(Decimal('19.9999999999999999'))
'19.9999999999999999'
like image 88
intgr Avatar answered Dec 24 '22 10:12

intgr