0

I have a field 'winning' in firestore database whose value is 988.95 . enter image description here

I want to decrease value by 500 or whatever user inputs in ediitext. Suppose here user entered 500. But by doing FieldValue.increment(-1*(Double.parseDouble(edittext.getText().toString().trim()))) ;

writes value 488.95000000005 in database enter image description here

Why is it even happening? Why cant just 488.95 be written in firestore?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-create-the-database-schemas-for-our-firebase-shopping-app-part-2-29f8bcac7acb) will help, as it explains why it is not recommended to use floating point numbers. – Alex Mamo Mar 06 '23 at 08:32
  • @AlexMamo it's paywalled – Risal Fajar Amiyardi Aug 07 '23 at 04:53

1 Answers1

1

What you're seeing is quite common in any system that uses floating point to store fractional numerical values.

The normal way to prevent this is to not store monetary amounts in floating point values, but either storing them in a fixed point value or in whole numerical values of the smallest denomination of the currency.

In Firestore the latter option would be the only way to go, meaning you'd store the value of winnning as cents. So

winning: 48895

As long as you make sure to only perform operations with other whole numbers, the value will remain an integer/long and the only time you'll have to devide it by 100 is to display the value to the user.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807