I have float value as follow:
6.07345232904e+23
How can I convert this to two decimal places?
I have tried with round()
.
But it is not working.
I have float value as follow:
6.07345232904e+23
How can I convert this to two decimal places?
I have tried with round()
.
But it is not working.
You can't. That value is approximately 607345232904000000000000, which already has more than two decimal places. If you want the representation to have two decimal places then you must specify that.
>>> '{:.3g}'.format(6.07345232904e+23)
'6.07e+23'
To answer your clarification of what you actually want to do, namely comparing two numbers with a given precision:
There are different ways to do this, depending on what your criteria are. The simplest solution is
abs(a-b) <= tolerance
If you are using Python 3.5, you can use math.isclose. For earlier version, this should be functionally equivalent
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
If you really need to handle all corner cases, you will have to to some additional work.