Posts Tagged ‘floating point number’

Getting python to print 5 digits of accuracy in the current time in seconds

Monday, January 11th, 2010

In the python shell if I type:


import time
time.time()

I get the current time in seconds with 5 digits past the decimal place of accuracy:


1263245893.382139

If I want to use this as a unique ID then I need to have this value as a string. Namely I need to be able to print it. But if I issue:


print time.time()

I only get 2 digits of accuracy past the decimal place:


1263245893.38

This seems to be because print when converting the time to a string is rounding its float value someplace. To solve this I use instead:


print "%f" %  time.time()

Which again returns all of the accuracy places I original had:


1263245893.382139

Finally to save this value as a string I just remove the print and instead have a variable on the left hand side of an equals sign:


current_time = "%f" %  time.time()

Rounding floats to ints with bc in bash

Sunday, August 16th, 2009

I’ve seen a lot of bizarre attempts to round floating point numbers to integers in bash. Here’s my cheap hack using bc:


echo "($float+0.5)/1" | bc

If your floating point number is in a variable called float then this will round up or down accordingly. As in 1.0 and 1.4 round to 1, while 1.5 and 1.9 round to 2.