Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: allow a FloatField or an IntegerField in an input form?

Tags:

django

I have a Django model with a field for price:

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

The issue is that my users might enter a price as 245 or as 245.00, and I want the system to be able to handle either.

Can I do something clever to allow this?

like image 983
AP257 Avatar asked Dec 01 '10 18:12

AP257


1 Answers

I don't understand why you need to do anything at all. A float doesn't have to have a floating-point component - 245 is just as valid a float as 245.00.

I would second maikhoepfel's recommendation that you don't use floats for prices, though. Floating point isn't able to represent certain decimal values exactly - this is a limitation of the standard IEEE floating-point algorithm. However, I'd recommend you use DecimalField instead, as this is ideal for values with a fixed number of decimal places, like prices.

like image 107
Daniel Roseman Avatar answered Oct 01 '22 02:10

Daniel Roseman