如何将数字截断为 3 位小数 [英] How to truncate a number to 3 decimals
本文介绍了如何将数字截断为 3 位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何在 MongoDB 中舍入一个数字.我只找到了如何使用 2 个小数但没有找到更多小数的方法.
I do not know how to round a number in MongoDB. I only find how to do it with 2 decimals but not with more decimals.
"location" : {
"type" : "Point",
"coordinates" : [
-74.00568,
40.70511
]
}
这些是我需要在点后用 3 个数字四舍五入的坐标示例.谢谢
These is an example of a coordinate that I need to round with 3 numbers after the dot. Thank you
推荐答案
对于 3 位小数四舍五入,您可以使用此公式.
For 3 decimal rounding, you can use this formula.
$divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ]
例如,使用您的示例数据,并使用此聚合:
For example, with your sample data, and using this aggregation:
db.getCollection('Test2').aggregate([
{ $project :
{
"location.type" : "$location.type",
"location.coordinates" :
{
$map:
{
input: "$location.coordinates",
as: "coordinate",
in: { $divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ] }
}
}
}
}
])
你可以获得想要的结果.
you can obtain the desired result.
{
"_id" : ObjectId("59f9a4c814167b414f6eb553"),
"location" : {
"type" : "Point",
"coordinates" : [
-74.005,
40.705
]
}
}
这篇关于如何将数字截断为 3 位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文