0

I came across a weird behaviour when saving a double value on mongodb with mongoose v5.11.15

I have to double values: this amount: 0.6 item amount: 0.3

the sum shoud be 0.9

however on the Database the value is saved as 0.89999999999

This is my code:

try {
        console.log('this amount: ', this.amount)
        console.log('item amount: ', item.amount)
        this.amount = this.amount + item.amount
        await this.save()
    } catch (e) {
        console.log(e)
    }

Has anyone come across this behaviour? is there a way to store the exact value?

Hector Toro
  • 351
  • 4
  • 18
  • 1
    open you chrome console and try `0.6 + 0.3` and [see this here it may help you](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Mohamed Oraby Nov 22 '22 at 17:12
  • 1
    This is a floating point preicsion error since `0.9` doens't have a precise representation as a float. Mongo has some guidance on the topic https://www.mongodb.com/docs/manual/tutorial/model-monetary-data/#model-monetary-data. I'd suggest deciding up front if it really matters. Is there a functional difference in your application for `0.8999999999999` vs `9`? – CollinD Nov 22 '22 at 17:12
  • 2
    Thanks both for your comments, since I'm dealing with stock inventory, i gues this imprecision might not be a problem as i have specific rounding rules on the front end. I guess I will continue and check how it goes. – Hector Toro Nov 22 '22 at 17:20

0 Answers0