Home > front end >  How to round to at most 2 decimal places, if necessary using golang projection mongodb
How to round to at most 2 decimal places, if necessary using golang projection mongodb

Time:12-15

projectStage := bson.D{
{"$project", bson.D{
    {"_id", 0},
    {"name", "$_id"},
    {"total", 1},
    {"totalPagu", 1},
    {"idpagu", 1},
    {"pdn", bson.D{
        {"$round", bson.D{
            {"pdn", 1},
        }},
    },
    }},
},

}

I get an error here message:

$round only supports numeric types, not object

How can I reslove this?

CodePudding user response:

In the Go programming language, you can use the fmt.Sprintf function to round a float to at most 2 decimal places.

You can also use the math.Round function to round a float to the nearest integer, and then convert it to a string with the desired number of decimal places using fmt.Sprintf.

CodePudding user response:

The $round operator takes an array as its operand, specifying the number to round and the decimal places to round to:

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

You may use the bson.A type to specify an array (or simply []any). So use the following project document:

projectStage := bson.D{
    {"$project", bson.D{
        {"_id", 0},
        {"name", "$_id"},
        {"total", 1},
        {"totalPagu", 1},
        {"idpagu", 1},
        {"pdn", bson.D{
            {"$round", bson.A{"$pdn", 2}},
        }},
    }},
}
  • Related