0

I want to round off some values for my numerical calculations in views like-------

5.5 to 5 OR 549 t0 500 and 599 - 600 (the nearest one)

So I want to use round off OR floor function in django as we used in other languages. Is there any functions related to this in django then please suggest me some functions and also the libraries which i have to import to use these functions.

Thanks.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
user1746291
  • 323
  • 2
  • 5
  • 15
  • This answer may halp you: http://stackoverflow.com/questions/3348825/how-to-round-integers-in-python – Lukasz Koziara Jan 28 '13 at 11:11
  • Could you provide some more examples how you expect the rounding to happen? e.g. what should 45 become, how about 450, 4500, 49, 490 and 4990? – bikeshedder Jan 29 '13 at 09:57

4 Answers4

2

You don't say if you're trying to do this in a template or elsewhere.

In a template, you can use the floatformat filter.

Otherwise, it's just Python, so you can use the normal Python rounding functions.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

When working with floats you can use round, math.ceil and math.floor.

For decimal.Decimal you can use the quantize method which allows you to specify the rounding:

value = decimal.Decimal('0.5')
value.quantize(decimal.Decimal('1'), decimal.ROUND_UP)
value.quantize(decimal.Decimal('1'), decimal.ROUND_DOWN)
value.quantize(decimal.Decimal('1'), decimal.ROUND_HALF_UP)
...

For a list of rounding methods see decimal.Context.

Beware that python uses ROUND_HALF_EVEN by default which is great for statistics but very awkward for financial math. A typical way to round a money amount to centis is the following piece of code:

amount = decimal.Decimal('0.15234')
CENTI = decimal.Decimal('0.01')
value.quantize(CENTI, decimal.ROUND_HALF_UP)
bikeshedder
  • 7,337
  • 1
  • 23
  • 29
0

Use decimal in your view:

>>> import decimal
>>> numbers = ['5.5','499','1','0.5']
>>> for i in numbers:
...   the_number = int(decimal.Decimal(i))
...   if the_number / 10:
...      the_number = the_number + 10 - (the_number % 10)
...   print the_number
...
5
500
1
0

If you want to format floats, use floatformat as suggested by Daniel, but it won't do the rounding for you.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • `decimal.Quantize(decimal.Decimal(10), decimal.ROUND_HALF_UP)` is way more concise and better readable. See my answer which shows how to do this. – bikeshedder Jan 29 '13 at 09:39
  • I don't think this code does what it is supposed to do. e.g. the number "10.1" returns 20. – bikeshedder Jan 29 '13 at 09:54
0

If you are doing it in the ORM, you can use a Func() expression, see this answer.

Community
  • 1
  • 1
mrts
  • 16,697
  • 8
  • 89
  • 72