Reputation: 333
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.
Upvotes: 0
Views: 2291
Reputation: 18925
If you are doing it in the ORM, you can use a Func()
expression, see this answer.
Upvotes: 0
Reputation: 7487
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)
Upvotes: 2
Reputation: 174624
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.
Upvotes: 0
Reputation: 599580
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.
Upvotes: 2