Django float or decimal unintentionally rounded when saved

I want to keep latitude and longitude in the Place model. I tried two fields: floatfield and decimalfield.

1. FloatField Model

class Place1(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()

2. DecimalField Model

class Place2(models.Model):
    latitude = models.DecimalField(max_digits=18, decimal_places=16)
    longitude = models.DecimalField(max_digits=19, decimal_places=16)

Both fields work well with values ​​below.

10.1
10.12
10.123
10.1234
...
10.1234567890123

However, after the 16th day (not “sixteen decimal places”), it is inadvertently rounded when stored .

place1 = Place1.objects.create(
            latitude=10.123456789012345,
            longitude=100.123456789012345
         )

>>place1.latitude
10.123456789012345 # works well

>>place1.longitude
100.123456789012345 # works well

# Unintentionally rounded when I get object from db. 
>>Place.objects.last().latitude
10.12345678901235 # unintentionally rounded

>>Place.objects.last().longitude
100.1234567890123 # unintentionally rounded



place2 = Place2.objects.create(
        latitude=Decimal('10.123456789012345'),
        longitude=Decimal('100.123456789012345')
     )

>>place2.latitude
Decimal('10.1234567890123450') # works well

>>place2.longitude
Decimal('100.1234567890123450') # works well

# Unintentionally rounded when I get object from db. 
>>Place.objects.last().latitude
Decimal('10.1234567890123500') # unintentionally rounded

>>Place.objects.last().longitude
Decimal('100.1234567890123000') # unintentionally rounded

I cannot find any explanation for this "unintentional round" in the django document. Please help. Thank.

+4
1

" " django docs, django .

MYSQL, , - Float.

, , FLOAT DOUBLE PRECISION .

, . .

DecimalField.

, DecimalField, . , - Float, Decimal.

, .

SQL ALTER TABLE your_table MODIFY latitude decimal(m,n);, OR

MYSQL Workbench , ( )

DECIMAL NUMERIC . ,

DECIMAL ( ); : DECIMAL (m, n)

(m) , , (n) , .

, , .

, .

+1

Source: https://habr.com/ru/post/1648854/


All Articles