Cheang Wai Bin
Cheang Wai Bin

Reputation: 191

PYTHON How to convert string into int or float

I tried to code a simple calculator but as a beginner I don't know how to actually convert my input strings into float or int. I want the output to be integer when it is 2 but not 2.0 while the output to be 2.5 when its a float. But I coded this and entered 1 + 1 I still get 2.0

from ast import literal_eval

# User input a simple calculation
num1, operator, num2 = input('Please enter a simple math calculation ').split()
num1 = float(num1)
num2 = float(num2)

# Convert string into either int or float
def convertString1 (num1):
    val = literal_eval(num1)
    return isinstance(val, int) or (isinstance(val, float) and val.is_integer())
def convertString2 (num2):
    val = literal_eval(num2)
    return isinstance(val, int) or (isinstance(val, float) and val.is_integer())


# Condition to perform calculation and output
if operator ==  "+" :
    print("{} + {} = {}".format(num1, num2, num1+num2))
elif operator == "-" :
    print("{} - {} = {}".format(num1, num2, num1-num2))
elif operator == "*" :
    print("{} * {} = {}".format(num1, num2, num1*num2))
elif operator == "/" :
    print("{} / {} = {}".format(num1, num2, num1/num2))
else :
    print("Syntax error")

Upvotes: 1

Views: 1137

Answers (2)

puf
puf

Reputation: 471

It is better to add if statement. For example

if int(res) == res:
    res = int(res)

Upvotes: 2

RagingRoosevelt
RagingRoosevelt

Reputation: 2164

The reason your numbers are displaying that way is because you're evaluating num1 and num2 as floats. If you wanted to test if you have an int, you could try something like if int(num1) == num1: to decide if you want to apply additional formatting. That leads into altering how it displays:

If all you're concerned with is how it displays, since you're already using format, try something like

"{:.0f}".format(a)

This will round the value, however, if you're sure that it's an int, then rounding it won't have any affect apart from visual.

Upvotes: 0

Related Questions