5

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?

1
  • 1
    And it does not work? float(245) is 245.00 ... Dec 1, 2010 at 18:23

2 Answers 2

6

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.

0
0

Best practice in dealing with prices usually dictate that you should be using an IntegerField anyway, because you might run into funky rounding/limited precision errors otherwise. Just divide/multiply by 100.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.