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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With