MongoDB number precision when using $inc in node/mongoose MongoDB number precision when using $inc in node/mongoose mongoose mongoose

MongoDB number precision when using $inc in node/mongoose


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'.