简体   繁体   中英

how to extract digits from a float in python

I have a floating point variable ie

123.456

how can I extract 12 ?

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'
>>>

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.' ).

  • 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM