【问题标题】:How to truncate a number to 3 decimals如何将一个数字截断为 3 位小数
【发布时间】:2018-04-12 19:14:32
【问题描述】:

我不知道如何在 MongoDB 中对数字进行四舍五入。我只发现如何使用 2 位小数而不是更多的小数。

"location" : {
    "type" : "Point",
    "coordinates" : [ 
        -74.00568, 
        40.70511
    ]
}

这些是我需要在点后用 3 个数字四舍五入的坐标示例。 谢谢

【问题讨论】:

标签: mongodb rounding


【解决方案1】:

对于 3 位小数舍入,您可以使用此公式。

$divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ]

例如,使用您的示例数据,并使用此聚合:

db.getCollection('Test2').aggregate([
    { $project : 
        { 
            "location.type" : "$location.type",
            "location.coordinates" :  
            { 
                $map: 
                {
                    input: "$location.coordinates",
                    as: "coordinate",
                    in: { $divide: [ {$trunc: { $multiply: [ "$$coordinate" , 1000 ] } }, 1000 ] }
              }
            }   
        } 
    }
])

你可以获得想要的结果。

{
    "_id" : ObjectId("59f9a4c814167b414f6eb553"),
    "location" : {
        "type" : "Point",
        "coordinates" : [ 
            -74.005, 
            40.705
        ]
    }
}

【讨论】:

    【解决方案2】:

    从 Mongo 4.2 开始,有一个新的 $trunc 聚合运算符,可用于截断 数字 到指定的小数位:

    { $trunc : [ , ] }

    可以在聚合管道中使用(这里我们将xs 截断为3 小数位):

    // db.collection.insert([{x: 1.23456}, {x: -9.87654}, {x: 0.055543}, {x: 12.9999}])
    db.collection.aggregate([{ $project: { "trunc_x": { $trunc: ["$x", 3] }}}])
    // [{"trunc_x": 1.234}, {"trunc_x": -9.876}, {"trunc_x": 0.055}, {"trunc_x": 12.999}]
    

    请注意,place 参数是可选的,省略它会导致截断为整数(即​​截断到小数点后 0 位)。

    如果您对舍入而不是截断感兴趣,还请注意等效的 $round 运算符。

    【讨论】:

      【解决方案3】:

      使用坐标(就像您在数组中一样),您可以分两步将它们截断:

      1. $arrayElemAt
      2. $trunc

      让它动起来:

       {'$project':{ 
          'lat': {'$trunc': [{ '$arrayElemAt': [ "$location.coordinates", 0 ] },2]},
          'lon': {'$trunc': [{ '$arrayElemAt': [ "$location.coordinates", 1 ] },2]}, 
       },
      

      我假设您在坐标中的第一个值是纬度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 2020-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多