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.

4

4 回答 4

2
于 2013-01-28T11:08:56.027 回答
2

使用浮点数时,您可以使用roundmath.ceilmath.floor

对于decimal.Decimal,您可以使用quantize方法,该方法允许您指定舍入:

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)
...

有关舍入方法的列表,请参见decimal.Context

请注意,python 默认使用 ROUND_HALF_EVEN,这对于统计非常有用,但对于金融数学却非常尴尬。将金额四舍五入为 centis 的典型方法是以下代码:

amount = decimal.Decimal('0.15234')
CENTI = decimal.Decimal('0.01')
value.quantize(CENTI, decimal.ROUND_HALF_UP)
于 2013-01-28T12:02:46.090 回答
0

decimal在您的视图中使用:

>>> 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

如果您想格式化浮点数,请floatformat按照 Daniel 的建议使用,但它不会为您进行舍入。

于 2013-01-28T11:14:21.953 回答
0

如果您在 ORM 中执行此操作,则可以使用Func()表达式,请参阅此答案

于 2016-01-05T22:49:59.133 回答