Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Multiply Decimals in Python

Tags:

python

decimal

I was writing a pounds to dollars converter program. I encountered some problems multiplying the two numbers.

pounds = input('Number of Pounds: ')
convert = pounds * .56
print('Your amount of British pounds in US dollars is: $', convert)

Can anyone tell me the code to correct this program?

like image 793
matthewpg123 Avatar asked Feb 15 '15 01:02

matthewpg123


People also ask

How do you multiply the decimals?

To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.

How do you multiply points in Python?

Python Multiplication – Arithmetic Operator Python Multiplication Operator takes two operands, one on the left and other on the right, and returns the product of the these two operands. The symbol used for Python Multiplication operator is * .

How do you get 2 decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

Can you multiply floats in Python?

Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float . The multiplication result will always be of type float .


1 Answers

In Python 3 input will return a string. This is basically equivalent of raw_input in Python 2. So, you need to convert that string to a number before performing any calculation. And be prepared for "bad input" (i.e: non-numeric values).

In addition, for monetary values, it is usually not a good idea to use floats. You should use decimal to avoid rounding errors:

>>> 100*.56
56.00000000000001
>>> Decimal('100')*Decimal('.56')
Decimal('56.00')

All of that lead to something like that:

import decimal

try:
    pounds = decimal.Decimal(input('Number of Pounds: '))
    convert = pounds * decimal.Decimal('.56')
    print('Your amount of British pounds in US dollars is: $', convert)
except decimal.InvalidOperation:
    print("Invalid input")

Producing:

sh$ python3 m.py
Number of Pounds: 100
Your amount of British pounds in US dollars is: $ 56.00

sh$ python3 m.py
Number of Pounds: douze
Invalid input
like image 130
Sylvain Leroux Avatar answered Sep 21 '22 09:09

Sylvain Leroux