-1

I need to convert user input to int. Below is what I have written so far which is not working out. It only accepts int. the end goal is to have a user inputs float (e.g 4.5) and the output would be (4).

i = input("Enter any value: ")

print(int(i))
Michel_T.
  • 2,741
  • 5
  • 21
  • 31
Coding
  • 1
  • 3

3 Answers3

2

int accepts integer string or a float but cannot handle float strings. So convert to float first and then convert to integer. If the input is invalid format, int(i) would raise ValueError exception, so you can use it to handle invalid inputs.

i = input("Enter any value: ")

try:
  print(float(int(i))
except ValueError:
  print("Please enter a number")
Shashank V
  • 10,007
  • 2
  • 25
  • 41
0

The input are in string format so first you need to convert it into float and then from float to int

You can do

i = input("Enter any value: ")

print(int(float(i)))

or you can do

i = float(input("Enter any value: "))

print(int(i))
Shubham Shaswat
  • 1,250
  • 9
  • 14
0

Apart from the other answers, you can use round() function:

i = input("Enter any value: ")
print(round(i))

But if you want to simply cut the decimal part, you can use math lib and floor():

import math
i = input("Enter any value: ")
print(math.floor(i))
Radoslaw Dubiel
  • 122
  • 2
  • 9