Python Forum
Why int() cannot pass a string representation of a float into int?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why int() cannot pass a string representation of a float into int?
#1
Dear all,
I have a rookie question.

In the following codes, we know that the second one will result in a ValueError, because the "int()" command cannot pass a string representation of a float into int. But why "float()" can do the opposite? Why "float()" can pass a string representation of an integer into float, when int() cannot pass a string of float into integer?
print (int("4"))
print (int("4.1"))
print (float("4"))
print (float("4.1"))
I know how to solve it by converting the string representation of a float into float first: print (int(float("4.1"))), but I am just curious why.

Many thanks in advance!
Reply
#2
Because float will convert "4" to 4.0, which is a float. On the other hand, you simply can't have an integer with a value of 4.1, hence it fails.

You could try stuff like rounding off or truncating before passing a float value to the int() function.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  platform binary representation --- 3 questions Skaperen 4 858 Dec-05-2020, 03:50 AM
Last Post: Skaperen
  how to pass the interactive string to Popen subprocess maiya 1 670 Sep-18-2020, 09:36 PM
Last Post: Larz60+
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 941 Sep-07-2020, 08:02 AM
Last Post: perfringo
  ValueError: could not convert string to float: RandomCoder 3 2,320 Jul-27-2020, 07:38 AM
Last Post: ndc85430
  could not convert string to float player1681 4 3,274 May-22-2020, 12:10 PM
Last Post: buran
  could not convert string to float: C JamesW 2 2,485 Jan-29-2020, 04:56 PM
Last Post: JamesW
  How to check if user entered string or integer or float?? prateek3 5 7,896 Dec-21-2019, 06:24 PM
Last Post: DreamingInsanity
  File system representation in a data structure Alfalfa 1 826 Dec-18-2019, 01:56 AM
Last Post: Alfalfa
  Error in the code ->ValueError: could not convert string to float: ' ' eagleboom 1 1,903 Nov-29-2019, 06:19 AM
Last Post: ThomasL
  Pass by reference vs Pass by value leodavinci1990 1 977 Nov-20-2019, 02:05 AM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020