Python Forum
Why is this multiplication not working? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why is this multiplication not working? (/thread-1710.html)



Why is this multiplication not working? - klopeks - Jan-21-2017

Hello,I'm very new to Python, and I'm having trouble with some basic math.  I've getting a user to input a number and assigning it to a variable.  Then I'm multiplying it by the value of another variable, which I've set to 0.1 and displaying the result.  When the input is 3, and I multiply it by the other variable, instead of getting .3, I'm getting .3000000000004.

What could cause the multiplication to return what appears to be an incorrect value?


RE: Why is this multiplication not working? - Larz60+ - Jan-22-2017

Show the code, it's impossible to answer correctly without.


RE: Why is this multiplication not working? - klopeks - Jan-22-2017

testMultiplier=0.1
testInput=int(input("Enter a number"))
testOutput=testInput*testMultiplier
print (testOutput)


If I input 3 when asked, it spits out 3.000004


RE: Why is this multiplication not working? - snippsat - Jan-22-2017

Quote:instead of getting .3, I'm getting .3000000000004.
It's the way floating point arithmetic work,Basic Answers Python doc.
There is a Decimal module.
>>> 0.4 - 0.1
0.30000000000000004

>>> from decimal import Decimal
>>> Decimal('0.4') - Decimal('0.1')
Decimal('0.3')



RE: Why is this multiplication not working? - klopeks - Jan-22-2017

thanks, that was very helpful.