You can use this to round to 6 significant digits:
round(test, 6 - int(math.log10(test)))
The resulting value from that is
7.545721e+29
This works by using log10
from the math
module to get the power of 10 in test
, rounds it down to get an integer, subtracts that from 6 then uses round
to get the desired digits.
As noted by others, round
works to the given number of decimal places. The log10
and the rest figures how many decimal places are needed to get the desired number of significant digits. If the decimal places are negative, round
rounds to the left of the decimal point.
You should be aware that log10
is not perfectly accurate and taking the int
of that may be off from the expected value by one. This happens rarely but it does happen. Also, even if the computed value is correct, converting the value to string (such as when you print it) may give a different-than-expected result. If you need perfect accuracy you would be better off working from the string representation of the value.