简体   繁体   English

Mongodb:$四舍五入

[英]Mongodb: $round decimal

I'm trying to round the average salary to 2 decimal places.我正在尝试将平均工资四舍五入到小数点后 2 位。 I'm stumped, I can get either everyones salary to 2 decimal places我被难住了,我可以将每个人的薪水精确到小数点后 2 位

db.employees.aggregate([{$project: {_id: null, 'roundedSal':{$round: [{$avg: '$salary'}]}}}])

which returns返回

{ "_id": null, "roundedSal": 48501.24 } { "_id": null, "roundedSal": 45999.71 } { "_id": null, "roundedSal": 35554.54 } { "_id": null, "roundedSal": 47700 } { "_id": null, "roundedSal": 48123.25 } { "_id": null, "roundedSal": 44415.94 } { "_id": null, "roundedSal": 42925.26 } { "_id": null, "roundedSal": 31500.66 } { "_id": null, "roundedSal": 50500.25 } { "_id": null, "roundedSal": 48501.24 } { "_id": null, "roundedSal": 45999.71 } { "_id": null, "roundedSal": 35554.54 } { "_id": null, "roundedSal": 47700 } { "_id": null, "roundedSal": 48123.25 } { "_id": null, "roundedSal": 44415.94 } { "_id": null, "roundedSal": 42925.26 } { "_id": null, "roundedSal ": 31500.66 } { "_id": null, "roundedSal": 50500.25 }

or get the overall average或获得总体平均值

db.employees.aggregate([{$group: {_id: null, 'roundedSal':{$avg: '$salary'}}}])

{ "_id" : null, "roundedSal" : 43913.427777777775 }

but I can't manage to figure out how to round this to two decimal places without an error being thrown但我无法弄清楚如何将其四舍五入到小数点后两位而不会引发错误

Please read the mongo documentation it's one of the bestest documentantions in my opinion.请阅读mongo 文档,这是我认为最好的文档之一。

// { $round : [ <number>, <place> ] }

db.employees.aggregate([{$project: {_id: null, 'roundedSal':{$round: [{$avg: '$salary'}, 2]}}}])

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

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