0

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.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
akira
  • 521
  • 2
  • 5
  • 14
  • See: http://stackoverflow.com/a/8940627/50065 – BioGeek Oct 14 '15 at 07:00
  • What do you want exactly? `607[... 20 digits here].xy` or `6.07e+23`? – Łukasz Rogalski Oct 14 '15 at 07:00
  • Possible duplicate of [How can I format a decimal to always show 2 decimal places?](http://stackoverflow.com/questions/1995615/how-can-i-format-a-decimal-to-always-show-2-decimal-places) – BioGeek Oct 14 '15 at 07:01
  • I want to compare two values 6.07345232904e+23 and 2.07386846826e+23 I have written the code as follows: def compare(x, y): a = float(x.hash) b = float(y.hash) c = float("{0:.2f}".format(a)) d=float("{0:.2f}".format(b)) if c > d: return d/c return c/d – akira Oct 14 '15 at 07:05
  • 1
    why do you round the values to compare? [How to correctly and standardly compare floats?](http://stackoverflow.com/q/4548004/995714) [Most effective way for float and double comparison](http://stackoverflow.com/q/17333/995714) https://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them/ http://floating-point-gui.de/errors/comparison/ – phuclv Oct 14 '15 at 08:00
  • 2
    You probably have an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You should ask how to compare, not how to round – phuclv Oct 14 '15 at 08:01

2 Answers2

4

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'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

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.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119