Python Forum
int() problem when extracting part of decimal
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
int() problem when extracting part of decimal
#1
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.
Reply
#2
>>> 11.20-11
0.1999999999999993
please, read https://docs.python.org/3/tutorial/floatingpoint.html

https://en.wikipedia.org/wiki/Floating-point_arithmetic
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Reply
#4
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to use a variable in Python (2.x) to define decimal part? MDRI 4 2,345 May-07-2021, 12:39 AM
Last Post: MDRI
  testing for Decimal w/o importing decimal every time Skaperen 7 4,472 May-06-2019, 10:23 PM
Last Post: Skaperen
  Decimal problem hmillsar 2 4,151 Dec-02-2016, 06:17 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020