Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropping trailing '.0' from floats

Tags:

python

I'm looking for a way to convert numbers to string format, dropping any redundant '.0'

The input data is a mix of floats and strings. Desired output:

0 --> '0'

0.0 --> '0'

0.1 --> '0.1'

1.0 --> '1'

I've come up with the following generator expression, but I wonder if there's a faster way:

(str(i).rstrip('.0') if i else '0' for i in lst) 

The truth check is there to prevent 0 from becoming an empty string.

EDIT: The more or less acceptable solution I have for now is this:

('%d'%i if i == int(i) else '%s'%i for i in lst) 

It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.

like image 890
Algorias Avatar asked Dec 22 '08 01:12

Algorias


People also ask

How do you remove floating trailing zeros?

To remove the trailing zeros from a number, pass the number to the parseFloat() function. The parseFloat function parses the provided value, returning a floating point number, which automatically removes any trailing zeros.

How do I print float values without trailing zeros?

To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.

Should you use trailing zeros?

For example, in pharmacy, trailing zeros are omitted from dose values to prevent misreading. However, trailing zeros may be useful for indicating the number of significant figures, for example in a measurement. In such a context, "simplifying" a number by removing trailing zeros would be incorrect.


1 Answers

See PEP 3101:

 'g' - General format. This prints the number as a fixed-point       number, unless the number is too large, in which case       it switches to 'e' exponent notation. 

Old style (not preferred):

>>> "%g" % float(10) '10' 

New style:

>>> '{0:g}'.format(float(21)) '21' 

New style 3.6+:

>>> f'{float(21):g}' '21' 
like image 180
ebas Avatar answered Sep 23 '22 04:09

ebas