user4633748
user4633748

Reputation:

Python: How to use decimals instead of rounding?

Ok, I know how to normally use decimals with mathematical calculations in Python. But these use variables. So I do not know how to do it in my instance. This is a calculator I typed up real quick but I do not know how to use decimals. Thanks a lot!!

def addition(a, b):
    return a + b

def subtraction(a, b):
    return a - b

def multiplication(a, b):
    return a * b

def division(a, b):
    return a / b

print """\nThis is a calculator. You can add, subtract, multiply, or divide with a max of two variables."""

print """\nTo add: Type 1
\nTo subtract: Type 2
\nTo multiply: Type 3
\nTo divide: Type 4 """

sign = raw_input("\n\nPlease enter a number  >")


if sign == "1":
    first = int(raw_input("\n\nEnter your first number to add  >"))
    second = int(raw_input("\n\nEnter your second number to add  >"))
    print "\nYour result is:\n"
    print addition(first, second)


elif sign == "2":
    first = int(raw_input("\n\nEnter your first number to subract  >"))
    second = int(raw_input("\n\nEnter your second number to subract  >"))
    print "\nYour result is:\n"
    print subtraction(first, second)

elif sign == "3":
    first = int(raw_input("\n\nEnter your first number to multiply  >"))
    second =int(raw_input("\n\nEnter your second number to multiply  >"))
    print "\nYour result is:\n"
    print multiplication(first, second)

elif sign == "4":
    first = int(raw_input("\n\nEnter your first number to divide  >"))
    second =int(raw_input("\n\nEnter your second number to divide  >"))
    print "\nYour result is:\n"
    print division(first, second)

Upvotes: 0

Views: 119

Answers (2)

solidpixel
solidpixel

Reputation: 12109

If you don't mind losing precision use floating point variables.

If you want to keep precision, I'd suggest using this:

https://docs.python.org/2/library/decimal.html

.. rather than rolling your own decimal maths library.

Upvotes: 1

wfr
wfr

Reputation: 701

Instead of int(...) use either float(...) or decimal.Decimal(...).

Example:

import decimal
d = decimal.Decimal(raw_input("\nEnter a number >"))
print(d)

or:

f = float(raw_input("\nEnter a number >"))
print(f)

Upvotes: 3

Related Questions