[英]How to round to at most 2 decimal places, if necessary using golang projection mongodb
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?我该如何解决这个问题?
In the Go programming language, you can use the fmt.Sprintf function to round a float to at most 2 decimal places.在 Go 编程语言中,您可以使用 fmt.Sprintf 函数将浮点数舍入到最多 2 位小数。
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.您还可以使用 math.Round 函数将浮点数四舍五入为最接近的整数,然后使用 fmt.Sprintf 将其转换为具有所需小数位数的字符串。
The $round
operator takes an array as its operand, specifying the number to round and the decimal places to round to: $round
运算符将一个数组作为其操作数,指定要舍入的数字和要舍入到的小数位:
{ $round : [ <number>, <place> ] }
You may use the bson.A
type to specify an array (or simply []any
).您可以使用
bson.A
类型来指定数组(或简单地[]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}},
}},
}},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.