Realm-js: Float decimals changes after create/update

Created on 29 Jun 2017  路  3Comments  路  Source: realm/realm-js

After inserting a float value of "90.99", the document stored is ... "90.9899978637695".

Is this a bug or on purpose?

T-Help

Most helpful comment

90.99 cannot be represented exactly by a 32-bit floating point value, which is what a property of type float requests (it can't be represented exactly as a 64-bit double precision floating point value either, for that matter). This article provides a good overview as to why. If you'd like to preserve the value exactly as you inserted it, you should use a property of type double, which is the same 64-bit double precision representation JavaScript uses for numeric values. While a double still won't store exactly the value 90.99, it will roundtrip exactly the same representation of the number that you have in your JavaScript code (which is really 90.9899999999999948840923025272786617279052734375).

All 3 comments

90.99 cannot be represented exactly by a 32-bit floating point value, which is what a property of type float requests (it can't be represented exactly as a 64-bit double precision floating point value either, for that matter). This article provides a good overview as to why. If you'd like to preserve the value exactly as you inserted it, you should use a property of type double, which is the same 64-bit double precision representation JavaScript uses for numeric values. While a double still won't store exactly the value 90.99, it will roundtrip exactly the same representation of the number that you have in your JavaScript code (which is really 90.9899999999999948840923025272786617279052734375).

Model :

Audit.schema = {
  name: 'Audit',
  primaryKey: 'id',
  properties: {
    rate: 'float?',
  }
};

Create/Update :

this.write(() => {
  audit = this.create('Audit', {
    rate: 1.9,
  }, true);
});

WTF :

console.log(audit.rate) // Output 1.899999976158142

Thanks to you @bdash, I solved my problem even if i find that a very, very strange behavior !

Working solution :

Audit.schema = {
  name: 'Audit',
  primaryKey: 'id',
  properties: {
    rate: 'double?',
  }
};

// ...

console.log(audit.rate) // Output 1.9

yeah need to change the type to Double in realm model fix this issue. Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timanglade picture timanglade  路  3Comments

ugendrang picture ugendrang  路  3Comments

CrystalRanita picture CrystalRanita  路  3Comments

fever324 picture fever324  路  4Comments

Chris-Petty picture Chris-Petty  路  3Comments