5
x = '16473.6'
y = str(int(float(x) * 1000))
print(y)

>>>16473599

OK... obviously I did something wrong... i know that these float thing are sometimes a little bit difficult from c#... but i thought that * 1000 should work... OK wrong

Can someone tell me how to do this better?

thank you very much

Akshay Mukadam
  • 2,388
  • 1
  • 27
  • 40
user2111880
  • 671
  • 9
  • 17

5 Answers5

4

Floating point numbers have always a problem with calculation as it's based on a binary approximation of numbers.

You may check Floating Point Arithmetic: Issues and Limitations

You may try using Decimal

x = '16473.6'
y = str(int(Decimal(x) * 1000))
print(y)
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
4

You may also want to try this :

x = '16473.6'
y = str(int(round(float(x) * 1000)))
print(y)

It gets rid of the float approximation.

ChoiBedal
  • 111
  • 7
3

That's an interesting demonstration of why you have to be careful with floating point numbers, and especially with converting them to int.

The essential problem is that the function int always rounds down, not "to the nearest".

So, even though:

>>> 16473.6
16473.6

it also true that:

>>> 16473.6*1000
16473599.999999998

It appears that the internal representation of your original floating point number was only correct to the first 16 or so decimal points. It was internally stored as 16473.599999999998 originally, and multiplication by 1000 has magnified that initial error, to a number just slightly lower than 16473600. Now int will round down to 16473599.

The resource posted by @R.T. is good reading for a more detailed explanation: Floating Point Arithmetic in Python

Community
  • 1
  • 1
cxrodgers
  • 4,317
  • 2
  • 23
  • 29
2

You should know that floats are not exact. This is because internal representation is in binary not decimal system.

Made up example 1: could really be represented as 0.999999999999. Now if you call int() on this, you won't get 1 but 0.

You can get around this by doing something like:

y = str(int(float(x) * 1000 + 0.5))
jure
  • 402
  • 5
  • 9
1

float has only limited precision. So after a certain number of digits (16 according to user2357112) it gets inaccurate. If the float is slightly below the nearest integer, you make a mistake when doing the conversion with int( ) only. Better wrap the argument with round( ):

x = '16473.6'
y = str(int(round(float(x) * 1000)))
print y

Output:

16473600
Falko
  • 17,076
  • 13
  • 60
  • 105