Beef Erikson
Beef Erikson

Reputation: 21

How to pick the first number after decimal point in Python 3.5?

I'm learning Python currently (love it so far) and have made a little Fahrenheit/Celsius converter.

This is the output upon running it:

Please enter the degrees in Fahrenheit or Celsius to convert: 32

32.0 degrees Celsius is 89.6 degrees Fahrenheit.

32.0 degrees Fahrenheit is 0.0 degrees Celsius.

Do you want to calculate again? (y/n):

Which is how I want it, except if the trailing number after the decimal is a 0 (a whole number), I'd like to drop the .0 entirely (i.e. 5.0 to 5). I'm guessing I'd want an if statement to test if it's equal to zero but how would I go about picking that value?

Full code:

answer = "ERROR"

def calcfc():
""" Calculates F to C and C to F, prints out,
    and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    print("\n{} degrees Celsius is {:.1f} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {:.1f} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()

Upvotes: 2

Views: 7446

Answers (8)

Ohad Eytan
Ohad Eytan

Reputation: 8464

You can use the modulo operator:

for num in [67.89, 123.0]:
    if num % 1 == 0:
        print(int(num))
    else:
        print(num)

#Output:
67.89
123

Upvotes: 0

halfer
halfer

Reputation: 20440

(Posted solution on behalf of the OP).

Fixed / working code is below and added additional function for repeating as per suggestion (thanks Daniel!). Figured I'd leave in case anyone has a use.

def calcfc():
    """ Calculates F to C and C to F, prints out,
        and asks if user wants to run again """
    try:
        degrees = float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: "))
    except Exception:
        print("\nPlease enter a valid number.")
        calcfc()

    ctof = (degrees * 9) / 5 + 32
    ftoc = (degrees - 32) * 5 / 9

    # checks if it's a whole number and gets rid of decimal if so
    degrees_text = "{:.1f}".format(degrees)
    ctof_text = "{:.1f}".format(ctof)
    ftoc_text = "{:.1f}".format(ftoc)
    if ctof_text.endswith(".0"):
        ctof_text = ctof_text[:-2]
    if ftoc_text.endswith(".0"):
        ftoc_text = ftoc_text[:-2]
    if degrees_text.endswith(".0"):
        degrees_text = degrees_text[:-2]

    print("\n{} degrees Celsius is {} degrees Fahrenheit.".format(degrees_text, ctof_text))
    print("{} degrees Fahrenheit is {} degrees Celsius.".format(degrees_text, ftoc_text))
    runagain()

def runagain():
    answer = input("\n\nDo you want to calculate again? (y/n): ")
    answer = answer.lower()
    # run again?
    while answer != "y" and answer != "n":
        answer = input("\nPlease enter y for yes or n for no: ")
    if answer == "y":
        calcfc()
    if answer == "n":
        exit()

calcfc()

Upvotes: 0

pramesh
pramesh

Reputation: 1954

try this. I have defined a function that strips off .0s from number. While printing I changed {:.1f} to {} as that would format it to a floating point number and there would be a decimal.

answer = "ERROR"

def remove0(initialValue):
  strValue = str(initialValue)

  if ("." in strValue):
    if(int(str(strValue.split(".")[1])) == 0):
      return int(strValue.split(".")[0])
    else:
      return initialValue
  else:
    return initialValue

def calcfc():
    """ Calculates F to C and C to F, prints out,    and asks if user wants to run again """
    try:
        degrees = remove0(float(input("\nPlease enter the degrees in Fahrenheit or Celsius to convert: ")))
    except Exception:
        input("\nEnter a valid number next time. Hit enter to terminate.")
        exit()

    ftoc = (degrees - 32) * 5 / 9
    ctof = (degrees * 9) / 5 + 32

    ftoc = remove0(ftoc)
    ctof = remove0(ctof)

    print("\n{} degrees Celsius is {} degrees Fahrenheit.".format(degrees, ctof))
    print("{} degrees Fahrenheit is {} degrees Celsius.".format(degrees, ftoc))
    global answer
    answer = input("\n\nDo you want to calculate again? (y/n): ")

calcfc()

# run again?
while answer != "y" and answer != "n":
    answer = input("\nPlease enter y for yes or n for no: ")
while answer == "y":
    calcfc()
if answer == "n":
    exit()

Upvotes: 0

Joe D
Joe D

Reputation: 388

Without adding any lines of code to your existing, you can use the g type to accomplish this in the format() call like so

'{0:g}'.format(5.5)

5.5

'{0:g}'.format(5.0)

5

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

Setup

ns = [32,32.0,32.04,32.05,32.1,32.45,32.5,32.51,32.6]

Solution

for n in ns:
    print('Before: {:.1f}'.format(n))
    #conditionally set the decimal place.
    print('After: {:.{}f}'.format(n, 0 if n%1 <0.05 else 1 ))

Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.0
After: 32
Before: 32.1
After: 32.1
Before: 32.5
After: 32.5
Before: 32.5
After: 32.5
Before: 32.5
After: 32.5
Before: 32.6
After: 32.6

Upvotes: 0

xssChauhan
xssChauhan

Reputation: 2838

You can get the decimal part of a number as follows:

>> num = 42.56
>> decimal_part = num - int(num)
>> decimal_part = 0.56

This post explores a similar question.

Upvotes: 1

Daniel
Daniel

Reputation: 42758

You have to convert the number to a string and test, if it ends with .0:

number = 23.04
text = "{:.1f}".format(number)
if text.endswith(".0"):
    text = text[:-2]

Upvotes: 4

Nir Alfasi
Nir Alfasi

Reputation: 53525

args = [89.6, 32.0, 5.5, 10.0, 9.1]

for var in args:
    if var == int(var):
        print int(var) # prints the number without the decimal part
    else:
        print var

OUTPUT

89.6
32
5.5
10
9.1

Upvotes: 0

Related Questions