3

I have a string in Python like that:

l = "0.00 0.00"

And I want to convert it in a list of two numbers.

The following instruction does not work:

int(l.strip(" \n").split(" ")[0])

Apparently the function int() can convert string like 0 or 00 to an int, but it does not work with 0.0.

Is there a way to convert 0.0?

A.

4
  • Integers cannot have decimal points. Commented May 26, 2014 at 16:51
  • In fact >>> int(0.0) is 0 ! Commented May 26, 2014 at 16:53
  • That code converts an existing double to an integer. Commented May 26, 2014 at 17:07
  • What would you expect 0.9 to be? What about 9.9? Truncate [0, 9] or round [1, 10]? Commented May 26, 2014 at 17:30

2 Answers 2

11

The easiest way to first convert to Decimal:

from decimal import Decimal
int(Decimal('0.00'))

if you are sure that fractional part is always zero then faster would be to use float

int(float('0.00'))
Sign up to request clarification or add additional context in comments.

Comments

0

For floating point conversion from a string you can use following, here assumption is that you need int for integral values in string

 def conv(st):
    try:
        return int(st)
    except ValueError: #If you get a ValueError
        return float(st)

 conv(l.strip(" \n").split(" ")[0])

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.