1

I want to roundup a number to 2 decimal places in python? How can I do that? I tried several things but failed.

So

  • (-0.012803683) will be -0.02
  • 0.478078191 will be 0.48
  • 0.450779926 will be 0.46

This question is about roundup, which is more different than round down

Sameera K
  • 1,298
  • 1
  • 17
  • 26
  • Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code! – Reblochon Masque May 18 '18 at 06:26
  • 2
    @ReblochonMasque I think this question is well formated and doesn't need to post any code.. – Qback May 18 '18 at 06:35
  • 2
    not a dupe as this is about rounding _up_, away from zero. – vidstige May 18 '18 at 06:48
  • @Arman this is not duplicate round up different than round down, and some of the answers in your link is wrong – Sameera K May 18 '18 at 07:57

3 Answers3

2

The following function works for all your examples

def roundup(x, places):
  d = 10 ** places
  if x < 0:
    return math.floor(x * d) / d
  else:
    return math.ceil(x * d) / d

>>> roundup(-0.012803683, 2)
-0.02
>>> roundup(0.478078191, 2)
0.48
>>> roundup(0.450779926, 2)
0.46
vidstige
  • 12,492
  • 9
  • 66
  • 110
2

You can try this :

import decimal

num = decimal.Decimal(-0.012803683).quantize(
          decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
print(num)
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
1
from math import ceil
a=-0.012803683
A=ceil(a*100)/100

That is how I would do it, but although this will work for your positive numbers, it gave A=-0.01 for the number that I put in the abouve code. Rounding up -0.012803683 would give you -0.01 though, so was that a mistake example? Or did you want to round down if it's a negative number?

from math import ceil
Round=lambda a:ceil(a*100)/100

Will allow you to do:

>>> Round(-0.012803683)
-0.01
>>> Round(0.478078191)
0.48
>>> Round(0.450779926)
0.46
Programmer S
  • 429
  • 7
  • 21