Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unicode to python float but keep the decimal places

Tags:

python

unicode

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.

like image 735
return 0 Avatar asked Dec 15 '22 06:12

return 0


1 Answers

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
like image 100
unutbu Avatar answered May 22 '23 07:05

unutbu