Python Forum

Full Version: Basic subtraction error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'll show it with some code:

Var1=str(input("What is Var1?")
#For example user inputs 8.10
Var2=str(input("What is Var2?")
#For example user inputs 6.80
Var1=float(Var1)
Var2=float(Var2)
Var3=Var1-Var2
print(Var3)
#The program then prints 1.2999999999999998
So the problem is it prints 1.2999999999999998 which is incorrect, as the correct answer is 1.30
My goal is to make it actually print the correct answer (for example if the user input 5.70 as Var1 and 3.90 as Var2, the correct answer would be 1.80)as I am creating a script to solve simultaneous equations.
Please let me know where I went wrong or how to make it print the correct answer if you know, thanks Smile
So there is no way to print precisely 1.30 or the correct answer in any case?
Firts, your original code - no need to wrap input() function in str(). input() returns str in any case.

As suggested by jefsummers - you can use Decimal, instead of float
from decimal import Decimal
var1=Decimal(input("What is Var1?"))
#For example user inputs 8.10
var2=Decimal(input("What is Var2?"))
#For example user inputs 6.80
var3 = var1 - var2
print(var3)
Another option is to use string formatting when printing the result of deduction
var1=float(input("What is Var1?"))
#For example user inputs 8.10
var2=float(input("What is Var2?"))
#For example user inputs 6.80
var3 = var1 - var2
print(f'{var3:.2f}')