0

The number I have = 52.003

The number I want = 52.00

The number I get after rounding to 2 decimal places:

    round(52.003, 2)
    >>> 52.0

How do I keep the second digit without Python automatically rounding it?

Dman42
  • 25
  • 6
  • 1
    http://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python – suvy May 06 '17 at 02:56
  • 1
    Possible duplicate of [How to format a floating number to fixed width in Python](http://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – suvy May 06 '17 at 02:56

3 Answers3

1

You can use the format() function in Python.

"{0:.2f}".format(round(52.003, 2))

You can also use the string formatting operator.

'%.2f' % 52.003
Nick Weseman
  • 1,502
  • 3
  • 16
  • 22
0

You can modify the output format like this:

a = 52.003
print "%.2f" % a
lta
  • 111
  • 4
0

Try this function :

import numpy as np
Round = lambda x, n: eval('"%.' + str(int(n)) + 'f" % ' + repr(x))
a = Round(52.003,2)
print a
>>> 52.00

Just indicate the number of decimals you want as a kwarg. However the result will be a string.

Ludovic Aphtes
  • 385
  • 1
  • 3
  • 8