You could use %g to achieve this:
'%g'%(3.140)
or, with Python ≥ 2.6:
'{0:g}'.format(3.140)
or, with Python ≥ 3.6:
f'{3.140:g}'
From the docs for format: g causes (among other things)
Answer from unutbu on Stack Overflowinsignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
You could use %g to achieve this:
'%g'%(3.140)
or, with Python ≥ 2.6:
'{0:g}'.format(3.140)
or, with Python ≥ 3.6:
f'{3.140:g}'
From the docs for format: g causes (among other things)
insignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
Me, I'd do ('%f' % x).rstrip('0').rstrip('.') -- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g, but, it works (and I don't know how to force %g to never use scientific notation;-).
I have a float formatted to 2 decimal places. I need to eliminate the 2nd decimal place if it's a "0" but still keep 2 decimal places open for when its 2 whole numbers.
number = float(25.20458)
print(format(number, ".2f"))
#Comes out as 25.20
#Need 25.2Windows 10 and Python 3.7
Updated Generalized to maintain precision and handle unseen values:
import decimal
import random
def format_number(num):
try:
dec = decimal.Decimal(num)
except:
return 'bad'
tup = dec.as_tuple()
delta = len(tup.digits) + tup.exponent
digits = ''.join(str(d) for d in tup.digits)
if delta <= 0:
zeros = abs(tup.exponent) - len(tup.digits)
val = '0.' + ('0'*zeros) + digits
else:
val = digits[:delta] + ('0'*tup.exponent) + '.' + digits[delta:]
val = val.rstrip('0')
if val[-1] == '.':
val = val[:-1]
if tup.sign:
return '-' + val
return val
# test data
NUMS = '''
0.0000 0
0 0
123.45000 123.45
0000 0
123.4506780 123.450678
0.1 0.1
0.001 0.001
0.005000 0.005
.1234 0.1234
1.23e1 12.3
-123.456 -123.456
4.98e10 49800000000
4.9815135 4.9815135
4e30 4000000000000000000000000000000
-0.0000000000004 -0.0000000000004
-.4e-12 -0.0000000000004
-0.11112 -0.11112
1.3.4.5 bad
-1.2.3 bad
'''
for num, exp in [s.split() for s in NUMS.split('\n') if s]:
res = format_number(num)
print res
assert exp == res
Output:
0
0
123.45
0
123.450678
0.1
0.001
0.005
0.1234
12.3
-123.456
49800000000
4.9815135
4000000000000000000000000000000
-0.0000000000004
-0.0000000000004
-0.11112
bad
bad
You can use format strings if you want, but be aware that you might need to set your desired precision, as format strings have their own logic for this by default. Janneb suggests a precision of 17 in another answer.
'{:g}'.format(float(your_string_goes_here))
After thinking about this some more, though, I think the simplest and best solution is just to cast the string twice (as jathanism suggests):
str(float(your_string_goes_here))
Edit: Added clarification because of comment.
You can keep the zeros by formatting the output:
eg: if the output is 0.96,
x= 0.96
"{0:.4f}".format(x)
Output:
'0.9600'
The output will be a string though..
The below article might be a good read: https://docs.python.org/2/tutorial/floatingpoint.html
It explains why Python displays floats in the above format.
IEEE 754 floating point numbers (of which float is binary64) are not designed to hold precision information. If you need to do so then you should use decimal.Decimal instead.
>>> decimal.Decimal('0.70')
Decimal('0.70')
>>> print decimal.Decimal('0.70')
0.70
See the decimal documentation for full details.
You can use the normalize method to remove extra precision.
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
To avoid stripping zeros to the left of the decimal point, you could do this:
def normalize_fraction(d):
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
Or more compactly, using quantize as suggested by user7116:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
You could also use to_integral() as shown here but I think using as_tuple this way is more self-documenting.
I tested these both against a few cases; please leave a comment if you find something that doesn't work.
>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')
Answer from the Decimal FAQ in the documentation:
>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5.00'))
Decimal('5')
>>> remove_exponent(Decimal('5.500'))
Decimal('5.5')
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')