Reputation: 243
I have something like this.
"Amount": { "value": { "$trunc": [ "$Amount", 2] }
When my Amount field is 244.50, it omits 0 and makes it 244.5 How do I ensure that it is 244.50 by using $trunc or $round. It is ok if the value is in string but it has to have 0 at the end. Please help.
Upvotes: 0
Views: 817
Reputation: 243
So I went ahead and resolved it and hopefully it will be helpful for someone in the future. Here is my answer. You can use $trunc or $round.
{ "Amount": { "value": { "$toString": { "$trunc": [ {"$toDecimal": "$Amount"}, 2] } } }
It is important to note that in my case, I can have string as final output as I am using this value to populate for printing in a statement. I don't plan to use it for calculation purpose (in which case, you would not need this in the first place)
Upvotes: 2
Reputation: 14530
Use Decimal128:
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.insert({a:NumberDecimal('1.2020')})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.aggregate([{$project:{v:{$trunc:['$a',2]}}}])
{ "_id" : ObjectId("5f36d9ccad0dd0c8ef1cc0e2"), "v" : NumberDecimal("1.20") }
Upvotes: 0