0

I pass float number as string format in int('.0')

0.0 is valid floating point number, so why it is giving error?

3
  • 3
    Because integers are not floating-point. Commented Nov 20, 2018 at 1:55
  • Thanks for answering. int(2.1) gives 2 in return. so int convert it into int. Commented Nov 20, 2018 at 1:58
  • 3
    int('2.1') returns a value error too. Similarly int(0.1) returns 0. Commented Nov 20, 2018 at 2:01

3 Answers 3

3

From the documentation of int:

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace.

So it gives you ValueError because the string '.0' does not represent an integer literal.

Sign up to request clarification or add additional context in comments.

1 Comment

@Nishant: Notice how it doesn't say "the literal can be preceded by a .".
2

Because you can type cast one step at a time. For example you can convert float to int or string to int. Not a floating point string which here is 2steps.

Comments

0

You can do it if you remove the quotes and make it a float like:

int(.1)

But strings don't work if inside the string is a float, because they will think it's a number and will break saying '.' is not a numeric value, also the reason the above works is because:

>>> .1
0.1
>>> 

And:

float(0.1)

Works.

Note that even a real float in a string can't be converted into an integer:

>>> int('3.1')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    int('3.1')
ValueError: invalid literal for int() with base 10: '3.1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.