Django: allow FloatField or IntegerField in input form?

I have a Django model with a field for the price:

class Book(models.Model): title = models.CharField(max_length=200) price = models.FloatField(null=True, blank=True) 

The problem is that my users can enter the price as 245 or 245.00, and I want the system to be able to handle it.

Can I do something smart to solve this?

+4
source share
2 answers

I don’t understand why you should do anything at all. A float should not have a floating point component - 245 is as correct as a float as 245.00 .

I would prefer the maikhoepfel recommendation that you do not use float for prices. A floating point cannot represent certain decimal values ​​exactly - this is a limitation of the standard IEEE floating point algorithm. However, I would recommend using DecimalField , as this is ideal for values ​​with a fixed number of decimal places, such as prices.

+5
source

Best price practice usually dictates that you should use IntegerField anyway, because otherwise you may encounter fake roundish / limited precision errors. Just divide / multiply by 100.

0
source

All Articles