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?
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?
Share Improve this question edited Dec 20, 2019 at 17:23 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked Dec 20, 2019 at 16:35 SimonSimon 3741 gold badge5 silver badges15 bronze badges 5- Is this in Node or in browser? – matthew-e-brown Commented Dec 20, 2019 at 16:40
- @matthew-e-brown it is Node – Simon Commented Dec 20, 2019 at 16:41
- @T.J.Crowder Yes I also have seen this question. The problem is that I am not using mongoose, but the native driver. So the answers doesn't help me – Simon Commented Dec 20, 2019 at 16:45
- 1 @T.J.Crowder, no you have read everything correctly :), It was my fault because I was referring to the false object. Can you post it as an answer, so I can accept it? – Simon Commented Dec 20, 2019 at 17:02
- @Simon - :-) Done! I've undeleted the answer I'd posted briefly. Glad that helped! – T.J. Crowder Commented Dec 20, 2019 at 17:23
1 Answer
Reset to default 5You'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