Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: FloatField or DecimalField for Currency?

I am curious which one would be better fitting as a currency field ? I will do simple operations such as taking difference, the percentage between old and new prices. I plan to keep two digits after the zero (ie 10.50) and majority of the time if these digits are zero, I will be hiding these numbers and display it as "10"

ps: Currency is NOT dollar based :)

like image 308
Hellnar Avatar asked Apr 02 '10 20:04

Hellnar


People also ask

What is the difference between FloatField and DecimalField?

The FloatField class is sometimes mixed up with the DecimalField class. Although they both represent real numbers, they represent those numbers differently. FloatField uses Python's float type internally, while DecimalField uses Python's Decimal type.

What is FloatField?

FloatField is a floating-point number represented in Python by a float instance. This field is generally used to store huge floating point numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. Syntax: field_name = models.FloatField(**options)

How do I add a price field in Django?

Now Django does not have a built-in Price Field; however, a field which simulates money in Django can be easily created using the DecimalField. Django's DecimalField requires 2 parameters, one is max_digits and the other is decimal_places. max_digits is the total number of digits that is in the number specified.


1 Answers

Always use DecimalField for money. Even simple operations (addition, subtraction) are not immune to float rounding issues:

>>> 10.50 - 0.20 10.300000000000001  >>> Decimal('10.50') - Decimal('0.20') Decimal('10.30') 
like image 80
Seth Avatar answered Sep 29 '22 03:09

Seth