简体   繁体   中英

Convert unicode to python float but keep the decimal places

I have a unicode string x = u'12345678.87654321' , I want to convert it to float in python using

float(x)

It is converted to 12345678.88 instead. It seem like float() automatically rounds the number to two decimal places. I want to keep whatever is in the unicode string (less than 10 decimal places). What would be a good alternative?

EDIT: My apologies. The example I used is not tested. I will just use my real data: I have an unicode string u'1464106296.285190'. This is the one that cannot be converted to float and retain all decimal places.

Use a decimal.Decimal :

In [103]: import decimal

In [104]: D = decimal.Decimal

In [109]: D(u'1464106296.285190')
Out[109]: Decimal('1464106296.285190')

In [110]: float(u'1464106296.285190')
Out[110]: 1464106296.28519

In [111]: print(D(u'1464106296.285190'))
1464106296.285190

It converts just fine. Python floats can hold about 16 digits of precision. print is doing some default rounding in Python 2.7 to display it, but either way the value is converted the same. You can format the value to print more precision. Here's examples in Python 3 and 2. Note the conversion is accurate to 16 places.

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s=u'1464106296.285190'
>>> f=float(s)
>>> f
1464106296.28519
>>> format(f,'.30f')
'1464106296.285190105438232421875000000000'
>>> print(f)
1464106296.28519

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s=u'1464106296.285190'
>>> f=float(s)
>>> f
1464106296.28519
>>> format(f,'.30f')
'1464106296.285190105438232421875000000000'
>>> print(f)
1464106296.29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM