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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With