简体   繁体   中英

MongoDB number precision when using $inc in node/mongoose

I'm currently modeling a database using MongoDB in which users can transfer funds between accounts and buy products, the values of which are debited from their current balances. I'm working with a precision of two decimal places, for products values and for user's balance.

The problem is that when I add or subtract a value with decimal places using the $inc operator, in my user document I get some precision errors, like this:

{
    "balance": 31513.210000000003,
}

I'm using node and mongoose to manipulate my DB, and I know about the floating point inaccuracies of the language, but I'd like to know if there's any way to overcome this issue in my mongodb database and force it to always work with two decimal places, so when I query for an user with a positive balance, values like 0.00000000003 won't be detected, as it should be 0.

Is there any way to control this in mongodb?

Instead of using a double which uses floating point math you've got several other methods you can choose from that offer different pros and cons.

Integer

Represent the balance not in the whole units, but in the fractional units. So you store 123.45 as 12345. If the math is addition and subtraction then this is easy, and all you need to make sure of is that any time you represent a value you insert the . at the appropriate place, but you can write a single function for this.

Object

Represent it as two integers: one for the whole part and one for the fractional part (123 and 45). This makes the math harder, but potentially makes the output easier to manage, and harder to accidentally output the wrong value.

String

With a string you'll have to write all your own math, but the output can be simple as the stored value would be '123.45'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM