在mongodb中四舍五入到小数点后两位 [英] Rounding to 2 decimal places in mongodb

查看:24
本文介绍了在mongodb中四舍五入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的收藏

学生

{
    "first_name":"Harew",
    "last_name":"Jackson",
    "class":14,
    "fee": [
        { "tuition":48500.2456, "transportation":500 }
    ]
}

我需要根据 fee = 4500.24 过滤学生,它应该显示所有费用为 4500.24 的学生忽略小数点后的其他数字.

I need to filter student according to fee = 4500.24 and it should display all the students having fee 4500.24 ignoring other digits after the decimal point.

我在MongoDB:如何在查询中获得 N 位小数精度查询中的精度,但此处提供的解决方案在我的场景中不起作用,因为"$mod": [ "$amount.value", 0.01 ] 不适用于 BigDecimal 类型,在我的收藏中,我的费用类型为 BigDecimal.

I have searched in MongoDB: How to get N decimals precision in a query precision-in-a-query but the solution provided here does not work in my scenario since "$mod": [ "$amount.value", 0.01 ] is not applicable for BigDecimal type and in my collection I have fee type as BigDecimal.

以下解决方案似乎运行良好,但我不知道如何在 Scala 中实现这一点

The following solution seems to work well but I don't know how to implement this in Scala

db.collection.find({ 
    "$where": function() { 
        return Math.round(this.fee.school * 100)/ 100 === 1.12; 
    }
}) 

推荐答案

您可以轻松地将 BigDecimal 中的值四舍五入为特定精度,也可以同时将其转换为双精度值.例如: -

you can easily round up the values into specific precision from BigDecimal , also if you want you can convert it into double value at the same time . For Example : -

scala> val s :BigDecimal = 10.232s:BigDecimal = 10.232

scala> val s :BigDecimal = 10.232 s: BigDecimal = 10.232

scala> s.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDoubleres1: Double = 10.23//转换为双精度

scala> s.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble res1: Double = 10.23 // CONVERTED AS DOUBLE

scala> s.setScale(2, BigDecimal.RoundingMode.HALF_UP)res2: scala.math.BigDecimal = 10.23//舍弃

scala> s.setScale(2, BigDecimal.RoundingMode.HALF_UP) res2: scala.math.BigDecimal = 10.23 // Rouding Off

所以在 scala 中,您可以使用 setScale 而不是使用 math.Round.

So in scala instead of using math.Round you can use setScale.

这篇关于在mongodb中四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆