4

I am querying data from a MongoDB database (MongoDB Driver 3.3). Some values are stored in Decimal128 format. The problem is that the following object is returned instead of a number:

value: Decimal128 {
  _bsontype: 'Decimal128',
  bytes: <Buffer 80 7c 45 c7 c6 02 00 00 00 00 00 00 00 00 3e 30>
}

I have found no function to convert this object into a human readable number (native JavaScript 64-Bit number). Does someone know how to achieve this?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Simon
  • 354
  • 1
  • 5
  • 15

1 Answers1

4

You've said the answers to this question don't apply because you're "not using mongoose, but the native driver." I have to admit I haven't got into Mongoose or MongoDB. I'll take your word for it that that question's answers don't apply here.

But their concept does. The native driver's Decimal128 also has toString, returning the string version of the number (although the documentation is not clear on that), which you can convert to number via any of the usual means. Obviously that conversion will be lossy (that's unavoidable), but I assume you know that.

So assuming dec contains the number:

const num = +dec.toString(); // Unavoidably, this is a lossy conversion
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875