定义
$round$roundrounds a number to a whole integer or to a specified decimal place.$round通过以下语法实现:{ $round : [ <number>, <place> ] } 字段类型说明<number>数字
<place>整型
可选 可为能解析为 -20 到 100(不含)之间的整数的任意有效表达式。例如
-20 < place < 100。如果未指定,则默认为0。If
<place>resolves to a positive integer,$roundrounds to<place>decimal places.例如,
$round : [1234.5678, 2]四舍五入到小数点后两位并返回1234.57。If
<place>resolves to a negative integer,$roundrounds using the digit<place>to the left of the decimal.例如,
$round : [1234.5678, -2]使用小数点左边的第二位数字 (3) 并返回1200。If the absolute value of
<place>equals or exceeds the number of digits to the left of the decimal,$roundreturns0.例如,
$round : [ 1234.5678, -4]指定小数点左边的第四位数字。这等于小数点左边的位数,返回0。If
<place>resolves to0,$roundrounds using the first digit to the right of the decimal and returns rounded integer value.例如,
$round : [1234.5678, 0]会返回1235
行为
向偶数舍入
When rounding on a value of 5, $round rounds to the nearest even value. For example, consider the following sample documents:
{_id : 1, "value" : 10.5}, {_id : 2, "value" : 11.5}, {_id : 3, "value" : 12.5}, {_id : 4, "value" : 13.5}
$round : [ "$value", 0] 将返回以下内容:
{_id : 1, "value" : 10}, {_id : 2, "value" : 12}, {_id : 3, "value" : 12}, {_id : 4, "value" : 14}
值 10.5 最接近偶数值10,而值 11.5 和 12.5 最接近偶数值 12。与总是向上或向下舍入相比,舍入到最接近的偶数值可让舍入数据分布更加均匀。
浮点数的舍入精度
如果在小数点分隔符后打印一个具有 20 位的双精度点0.05,您将看到 0.05000000000000000278,它略大于 0.05,并四舍五入为 0.1。
MongoDB使用 IEEE 754 标准进行点计算,其行为与该标准一致。
If you need a floating point number for an application that requires high precison, consider a Decimal128 value. For details, see BSON.Decimal128.
如果需要存储货币值,请考虑使用最低货币面值单位的整数。示例,使用带分或便士的整数而不是点。
返回的数据类型
返回的数据类型与输入表达式或值的数据类型相匹配。
null、NaN 和+/- Infinity
If the first argument resolves to a value of
nullor refers to a field that is missing,$roundreturnsnull.If the first argument resolves to
NaN,$roundreturnsNaN.If the first argument resolves to negative or positive infinity,
$roundreturns negative or positive infinity respectively.
例子 | 结果 |
|---|---|
|
|
|
|
|
|
|
|
例子
使用以下文档创建名为 samples 的集合:
db.samples.insertMany( [ { _id: 1, value: 19.25 }, { _id: 2, value: 28.73 }, { _id: 3, value: 34.32 }, { _id: 4, value: -45.39 } ] )
以下聚合返回四舍五入到小数点后第一位的
value:db.samples.aggregate([ { $project: { roundedValue: { $round: [ "$value", 1 ] } } } ]) 操作返回以下结果:
{ "_id" : 1, "roundedValue" : 19.2 } { "_id" : 2, "roundedValue" : 28.7 } { "_id" : 3, "roundedValue" : 34.3 } { "_id" : 4, "roundedValue" : -45.4 } 以下聚合返回使用小数点左边第一位数字进行四舍五入的
value:db.samples.aggregate([ { $project: { roundedValue: { $round: [ "$value", -1 ] } } } ]) 操作返回以下结果:
{ "_id" : 1, "roundedValue" : 10 } { "_id" : 2, "roundedValue" : 20 } { "_id" : 3, "roundedValue" : 30 } { "_id" : 4, "roundedValue" : -50 } 以下聚合将返回四舍五入为整数的
value:db.samples.aggregate([ { $project: { roundedValue: { $round: [ "$value", 0 ] } } } ]) 操作返回以下结果:
{ "_id" : 1, "roundedValue" : 19 } { "_id" : 2, "roundedValue" : 29 } { "_id" : 3, "roundedValue" : 34 } { "_id" : 4, "roundedValue" : -45 }