简体   繁体   English

在 Mongodb 中使用 $trunc 或 $round 不能保证 2 位小数

[英]Using $trunc or $round in Mongodb does not guarantee 2 decimal places

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.当我的 Amount 字段为 244.50 时,它会省略 0 并将其设为 244.5 如何使用 $trunc 或 $round 确保它为 244.50。 It is ok if the value is in string but it has to have 0 at the end.如果值在字符串中是可以的,但最后必须有 0。 Please help.请帮忙。

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.您可以使用 $trunc 或 $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.重要的是要注意,在我的情况下,我可以将字符串作为最终的 output,因为我正在使用此值填充以在语句中打印。 I don't plan to use it for calculation purpose (in which case, you would not need this in the first place)我不打算将它用于计算目的(在这种情况下,您首先不需要它)

Use Decimal128:使用十进制128:

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") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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