Python Forum

Full Version: int() problem when extracting part of decimal
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys,
could anyone explain this please ?

def convert(val): 
    dollars = int(val) 
    #it returns 11 Ok 
 
    cents = 100*(val - dollars) 
    #it prints 20.0 Ok 
 
    #to get whole number of cents, I take only int part of the number 
    cents_1 = int(cents) 
    print "cents_1",cents_1 
#Why I get from 20.0 the value 19 ? From 20.0 I expect 20.


# Tests
convert(11.20)

I want to get dollars and cent separately from 11.20. I know, there are probably better ways, but I want to understand, why the int() does not work as I expect.

Why I get from 20.0 the value 19 ? From 20.0 I expect 20

Thank you.
thank you.
Actually I have been using http://www.codeskulptor.org/ which runs python 2.x and in that way it gives you 20.0
def convert(val): 
    dollars = int(val) 
    #it returns 11 Ok 
  
    cents = 100*(val - dollars) 
    #it prints 20.0 Ok 
    print(dollars, val, val-dollars, 100*(val-dollars))
    #to get whole number of cents, I take only int part of the number 
    cents_1 = int(cents) 
    print("cents_1",cents_1)

import sys
print('python version:', sys.version_info)
convert(11.20)
Output:
('python version:', sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)) (11, 11.2, 0.1999999999999993, 19.99999999999993) ('cents_1', 19)
In my case both 2 and 3 gives the same result.
You can check also at repl.it: https://repl.it/repls/SpryJaggedStrategy

Don't know why codeskluptor is giving 0.20, but you should be aware of the floating-point limitations.
(Mar-23-2020, 05:51 PM)buran Wrote: [ -> ]
>>> 11.20-11
0.1999999999999993
please, read https://docs.python.org/3/tutorial/floatingpoint.html

https://en.wikipedia.org/wiki/Floating-point_arithmetic

thank you. I got it.