Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a number to 3 decimals

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
    ]
}

These is an example of a coordinate that I need to round with 3 numbers after the dot. Thank you

like image 850
Abdel DOOFENSCHMIRTZ Avatar asked Oct 31 '17 14:10

Abdel DOOFENSCHMIRTZ


People also ask

How do you correct a number to 3 decimal places?

Rounding to the nearest thousandth means the same as rounding to 3 decimal places. For example, round 3.3685 to the nearest thousandth. The 3rd digit after the decimal point is 8 and so the choice is to round up to 3.369 or down to 3.368.

How do I reduce to 3 decimal places in Excel?

Round a number down by using the ROUNDDOWN function. It works just the same as ROUND, except that it always rounds a number down. For example, if you want to round down 3.14159 to three decimal places: =ROUNDDOWN(3.14159,3) which equals 3.141.


2 Answers

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
        ]
    }
}
like image 186
Serkan Arslan Avatar answered Oct 02 '22 10:10

Serkan Arslan


Starting Mongo 4.2, there is a new $trunc aggregation operator which can be used to truncate a number to a specified decimal place:

{ $trunc : [ <number>, <place> ] }

Which can be used as such within an aggregation pipeline (here we truncate xs to 3 decimal places):

// 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}]

Note that the place parameter is optional, and omitting it results in truncating to a whole integer (i.e. truncating at 0 decimal places).

Also note the equivalent $round operator if you're interested in rounding rather than truncating.

like image 23
Xavier Guihot Avatar answered Oct 02 '22 12:10

Xavier Guihot