1👍
✅
The answer is actually twofold.
-
How to store the data?
Do not store it as a CharField or something. Just store it as a DecimalField or a FloatField.
models.DecimalField(..., max_digits=20, decimal_places=10)
-
How to show only two decimals?
Use the template tag
floatformat
that takes the full value as input and outputs a decimal rounded with the number of decimals you want. In your case that would be{{ value|floatformat:2 }}
.
Note that floats and decimal fields are not the same.
[credit goes to Burhan Khalid for pointing out that a custom template tag is not needed]
0👍
The easiest way, if the datatype doesn’t matter, is to store it as text in the database and then just parse the amount when you show it.
>>> silly = '12345.6789098765'
>>> silly[:silly.rfind('.')+3]
'12345.67'
Slightly more advanced; assuming you don’t need precision:
>>> "{0:0.2f}".format(float(silly))
'12345.68'
Source:stackexchange.com