PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] Why doesn't the int() function convert a float to integer while in input() function?

 July 20, 2022     integer, python     No comments   

Issue

Why doesn't the int() function convert a float to integer while in input() function?

input_1 = input(f'enter the num: ')

try: 
    a = int(input_1)
    print(f"it is an integer")
except:
    print(f"no an integer")
    

input_1 = 3.532453

try: 
    a = int(input_1)
    print(f"it is an integer")
except:
    print(f"no an integer")

Result:

enter the num: 3.532453
no an integer
it is an integer

Solution

So you can change a decimal to an int in python. But not without losing all the data past the decimal point. For example if you convert "12.3356" to an int using int(float("12.3356") and the result would be 12.

An int value in python is one without a decimal point for eg: 3.

A float value in python is a number with a decimal point for eg: 3.141.

So, if you want to check if what a user enters is a number and conserve everything past the decimal point, convert the strings to a float instead of an int:

input_1 = input('enter the num: ')

try:
    a = float(input_1)
    print("it is a number")
except ValueError:
    print("not a number")

By using float() instead of int(), you get to keep all the data past the decimal point (if you need it in other parts of your program).

However, if you still want to convert a float to an int (and lose everything past the decimal point), you can do:

Note that the below is basically extra code for a disadvantage and the above is usually better (in most cases), but if that's what you want well here you go:

input_1 = input('enter the num: ')

try:
    a = int(float(input_1))
    print("it is a number")
except ValueError:
    print("not a number")


Answered By - Raed Ali
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing