Python function for removing zeroes right of decimal, including decimal point? [duplicate]

StackOverflow https://stackoverflow.com/questions/22693706

  •  22-06-2023
  •  | 
  •  

Question

I am using xlrd to read values from cells in an excel spreadsheet. Whenever I detect a cell type = 2, then I know it is a number. A number of 3 in cell will be returned as 3.0 And a number of 3.14 will be returned as 3.14

I will be converting numbers to text. What function should I use to remove zeroes right of the decimal and the decimal?

The above 2 numbers should be 3 and 3.14

Was it helpful?

Solution

Use str.rstrip(), twice:

str_of_float.rstrip('0').rstrip('.')

This will remove trailing zeros, and if that leaves you with a trailing . it's removed as well.

Demo:

>>> '3.14'.rstrip('0').rstrip('.')
'3.14'
>>> '3.0'.rstrip('0').rstrip('.')
'3'
>>> '3000.0'.rstrip('0').rstrip('.')
'3000'

Don't be tempted to use .rstrip('.0'); it'll remove too many zeros:

>>> '3000.0'.rstrip('.0')
'3'

OTHER TIPS

I always use format when printing values to strings. Using the format specs, it gives a good deal of control over what is printed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top