[Django]-Store decimal value in Django model

3đź‘Ť

Are you using python 2 ? In that case you need to do

latitude = latitude / 3600000.0
longitude = longitude / 3600000.0

In python 2, if you divide two integers, you get one integer as a result. Adding .0 at the end makes the denominator a float.

You could also do float(3600000).

And another option is “importing” the behaviour from python 3 using:

from __future__ import division
👤JoseKilo

1đź‘Ť

To be a bit clearer as to why the first answer sort-of-works – the issue here is that you’re creating an integer number, and then trying to coerce it to decimal.Decimal in the DB when you add it. It’s slightly unclear as to what your input number type on latitude is, but in the example given, you’re dividing an integer by an integer, which gives an integer…

if you do:

type(latitude/360000), it will output <type 'int'>

However, in the other answer given above, it will create a float type

type(latitude/360000.00) will output <type 'float'>

The conversion between float numbers and decimals should be explicit and not implicitly done – they are not the same thing. Given the accuracies you seem to be working to in that example, the implicit rounding may be significant.

A better route may be, as per this answer to use:

from decimal import Decimal
Decimal.from_float(latitude/3600000.00)
👤Withnail

Leave a comment