I\'m trying to display the output of my addition to more than 2 decimal places.
import time
import random
max_number = 1000000.0
random_time = random.randra
You'll find that if you hard-code the number of digits to print, you'll sometimes get too few or worse yet go past the floating-point precision and get meaningless digits at the end. The standard floating point number only has precision to about 15 digits. You can find out how many of those digits are to the right of the decimal point with this simple formula:
digits_right = 14 - int(math.log10(value))
Using that you can create an appropriate %f
format:
fmt = '%%0.%df' % max(0, digits_right)
>>> f = 1/7.
>>> repr(f)
'0.14285714285714285'
>>> str(f)
'0.142857142857'
>>> f
0.14285714285714285
>>> print f
0.142857142857
>>> '%.15f' % f
'0.142857142857143'
You already have the full number. Use a custom format specifier on output.
>>> print '%.15f' % range_key
1347053222.790798902511597
When turning a float into a string (printing does this automatically), python limits it to only the 12 most significant digits, plus the decimal point.
When returning the number from a function, you always get the full precision.
To print more digits (if available), use string formatting:
print '%f' % range_key # prints 1347053958.526874
That defaults to 6 digits, but you can specify more precision:
print '%.10f' % range_key # prints 1347053958.5268740654
Alternatively, python offers a newer string formatting method too:
print '{0:.10f}'.format(range_key) # prints 1347053958.5268740654