-1
def poundsToMetric(pounds):
    kilograms = pounds / 2.2
    grams = kilograms * 1000
    return int(kilograms), grams % 1000

pounds = float(input("How many Pounds? "))
kg, g = poundsToMetric(pounds)
print('The amount of pounds you entered is {}. '\
      'This is {} kilograms and {} grams.'.format(pounds, kg, g))

this program works but I am wondering how do I get the kilograms to be only even with decimal points so instead of 65 pounds being like 545.4544545454 grams I need it to be 545 grams

Derek G.
  • 63
  • 1
  • 2
  • 5
  • Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Hypaethral Oct 26 '15 at 21:02
  • Possible duplicate of [How do you round UP a number in Python?](http://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python) – Peter Uhnak Oct 26 '15 at 21:36

2 Answers2

0

There are two ways:

  1. Use round() built-in function

    def poundsToMetric(pounds):
        kilograms = pounds / 2.2
        grams = kilograms * 1000
        return int(kilograms), grams % 1000
    
    pounds = float(input("How many Pounds? "))
    kg, g = poundsToMetric(pounds)
    print('The amount of pounds you entered is {}. This is {} kilograms and {} grams.'.format(pounds, kg, round(g)))
    
  2. Use int() casting to get the Integer part of the value:

    def poundsToMetric(pounds):
        kilograms = pounds / 2.2
        grams = kilograms * 1000
        return int(kilograms), grams % 1000
    
    pounds = float(input("How many Pounds? "))
    kg, g = poundsToMetric(pounds)
    print('The amount of pounds you entered is {}. This is {} kilograms and {} grams.'.format(pounds, kg, int(g)))
    

See output for each of these ways, respectively, below:

➜  python help.py
How many Pounds? 65
The amount of pounds you entered is 65.0. This is 29 kilograms and 545.0 grams.

➜  python help.py
How many Pounds? 65
The amount of pounds you entered is 65.0. This is 29 kilograms and 545 grams.
Andrés Pérez-Albela H.
  • 4,003
  • 1
  • 18
  • 29
0

If you add the line

print type(grams%1000)

You will get the output

<type 'float'> 

So this is clearly returning a float number. Cast it to int to get the desired result.

Instead of doing this:

return int(kilograms), grams % 1000

Do this:

return int(kilograms), int(grams % 1000)

Now the output for your program is:

The amount of pounds you entered is 65. This is 29 kilograms and 545 grams.

Exactly what you wanted.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57