1👍
Mysql has an "truncate" function to round the values retrieved from queries. You could use an database function with ‘Truncate’ in the function argument
from django.db.models import Func,F
Func(F('item_value') * F('availability_percentage'), 2, function='Truncate', output_field=FloatField())
0👍
Are you restricted to a certain version of django
? If not, I believe the documentation references a precision
keyword argument to the Round
function that might suit your needs.
https://docs.djangoproject.com/en/4.1/ref/models/database-functions/#django.db.models.functions.Round
Rounds a numeric field or expression to precision (must be an integer) decimal places. By default, it rounds to the nearest integer. Whether half values are rounded up or down depends on the database.
I misread actually. You already are making use of precision in one of your examples, you’re just passing it in as a positional argument.
Looking at your implementation with Decimal
I think you have the right idea. However, using prec=2
or prec=3
seems to be referring to the precision of significant digits, so 9809.4069
with prec=2
is 9800 = 9.8 * 10^2
and prec=3
yields 9810 = 9.81 * 10^3
.
So, if your numbers are going to be floats
, you should use create_decimal
as you were, but don’t restrict the precision.
context = decimal.Context()
context.create_decimal(9809.4069)
>>> Decimal('9809.468999999999999996023488224')
Then you’d use quantize
, as described in the documentation, for the appropriate cut off when dealing with currency.
https://docs.python.org/3/library/decimal.html
The quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places
- [Answered ]-Why is my Docx converter returning 'None'
- [Answered ]-Can I use a python metaclass to keep track of subclasses in separate files?
- [Answered ]-Registration/authorization form with class-based generic views in django
- [Answered ]-Django: grouping cache
- [Answered ]-Build-dependencies for psycopg2 could not be satisfied