I'm not sure exactly what you want, but I assume you just want to round the numbers you have to the nearest integer? If so, you can use the built-in function round
:
>>> int(round(1.5))
2
Here's the help:
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
If you want to round down you can use floor
from math
. I think you actually want to use this after taking the logarithm, rather than just casting to int, as int(-0.5) is 0, not -1 as you want. Here's a modified version of your program that I think does what you want:
from math import log10, floor
def format_value_error(value,error):
E = int(floor(log10(error)))
val = int(round(float(value) / 10**E))
err = int(round(float(error) / 10**E))
return "(%d +- %d) x 10^%d" % (val, err, E)
print format_value_error(123, 12)
print format_value_error(4234.3, 2)
print format_value_error(0.02312, 0.003)
This gives the following output:
(12 +- 1) x 10^1
(4234 +- 2) x 10^0
(23 +- 3) x 10^-3
This is very close to what you want. The only difference is that the text x 10^0
should not be printed, but I'm sure you can find a solution for this. :)