1

I have a floating point variable i.e.

123.456

how can I extract 12 ?

1
  • 3
    Is that the left-most 2 characters or is that the 10's and 100's place numerically? Commented Jan 7, 2011 at 15:59

3 Answers 3

5

If you render the float as a string, then you can just index the digits you like:

str(123.456)[:2]

"proof" in shell:

>>> str(123.456)[:2]
'12'
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. int(str(123.456)[:2] is exactly what I was looking for
4

If you want to do it a "mathy" way, you could also divide by 1e<number of digits to strip>. For example:

>>> int(123.456 / 1e1) # 1e1 == 10
12
>>> int(123.456 / 1e2) # 1e2 == 100
1
>>> int(123.456 / 1e-1) # 1e-1 == 0.1
1234

This will be much faster than converting float -> string -> int, but will not always behave exactly the same way as the string method above (eg, int(1.2 / 1e1) will be 0, not '1.').

Comments

2
  • result as float:
123.456//10
# res: 12.0
  • result as integer
int(123.456)//10
# res: 12
  • res as string: you have to care about the position of . !
str(123.456)[:2]  
# res: "12"

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.