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
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 837 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  How to pass encrypted pass to pyodbc script tester_V 0 807 Jul-27-2023, 12:40 AM
Last Post: tester_V
  convert string to float in list jacklee26 6 1,820 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,769 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  Convert string to float problem vasik006 8 3,274 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  Detecting float or int in a string Clunk_Head 15 4,283 May-26-2022, 11:39 PM
Last Post: Pedroski55
  platform binary representation --- 3 questions Skaperen 4 2,712 Dec-05-2020, 03:50 AM
Last Post: Skaperen
  how to pass the interactive string to Popen subprocess maiya 1 1,846 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 2,514 Sep-07-2020, 08:02 AM
Last Post: perfringo
  ValueError: could not convert string to float: RandomCoder 3 5,701 Jul-27-2020, 07:38 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

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