Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a float from string

I have a simple string that I want to read into a float without losing any visible information as illustrated below:

s = '      1.0000\n'

When I do f = float(s), I get f=1.0

How to trick this to get f=1.0000 ?

Thank you

like image 793
Gökhan Sever Avatar asked Aug 28 '26 01:08

Gökhan Sever


1 Answers

Direct answer: You can't. Floats are imprecise, by design. While python's floats have more than enough precision to represent 1.0000, they will never represent a "1-point-zero-zero-zero-zero". Chances are, this is as good as you need. You can always use string formatting, if you need to display four decimal digits.

print '%.3f' % float(1.0000)

Indirect answer: Use the decimal module.

from decimal import Decimal
d = Decimal('1.0000')

The decimal package is designed to handle all these issues with arbitrary precision. A decimal "1.0000" is exactly 1.0000, no more, no less. Note, however, that complications with rounding means you can't convert from a float directly to a Decimal; you have to pass a string (or an integer) to the constructor.

like image 54
Chris B. Avatar answered Aug 30 '26 15:08

Chris B.



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!