Reputation: 645
How would you format a float to three signicant figures after a decimal place? If the float has no decimal places then the number should remain the same.
This is correct:
'{0:.3}'.format(0.000325658)
'0.000326'
This is incorrect:
'{0:.3}'.format(325256.023)
'3.25e+05'
and should be
325256.023
The value 325256.0
should be output as 325256.0
.
I'd like this to be done with a single ''.format()
if possible.
Test cases:
0.000325658 - > 0.000326
325256.023 - > 325256.023
325256.0 - > 325256.0 or 325256.000
Edit add new test case:
'{0:.3f}'.format(325256.000023)
'325256.000'
should be
325256.000023
Upvotes: 0
Views: 570
Reputation: 2032
If you're happy to include numpy then you could use the numpy.format_float_positional function, with an extra step:
import numpy as np
def to_significant_decimals(n, amount):
integer = int(n)
n -= integer
return integer + float(np.format_float_positional(n, precision=amount, unique=False, fractional=False))
tests = [ 0.000325658, 325256.023, 325256.0, 325256.000023, 0, 7, 1000000, 1000.3, 1000.0001, 1234.4321 ]
for test in tests:
print(' ' + str(test) + ' = ' + str(to_significant_decimals(test, 3)))
print(str(-test) + ' = ' + str(to_significant_decimals(-test, 3)))
The numpy function allows you to choose the amount of significant figures, but this includes the integer part. I've solved that by taking the integer part away, doing the format, then adding the integer back on. There's probably a more elegant solution, but this gives the results that you want.
Outputs:
0.000325658 = 0.000326
-0.000325658 = -0.000326
325256.023 = 325256.023
-325256.023 = -325256.023
325256.0 = 325256.0
-325256.0 = -325256.0
325256.000023 = 325256.000023
-325256.000023 = -325256.000023
0 = 0.0
0 = 0.0
7 = 7.0
-7 = -7.0
1000000 = 1000000.0
-1000000 = -1000000.0
1000.3 = 1000.3
-1000.3 = -1000.3
1000.0001 = 1000.0001
-1000.0001 = -1000.0001
1234.4321 = 1234.432
-1234.4321 = -1234.432
Upvotes: 1