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

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

问题描述

我的收藏为

学生

{
    "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中舍入为特定精度,也可以同时将其转换为double值. 例如:-

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.232 s:BigDecimal = 10.232

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

scala> s.setScale(2,BigDecimal.RoundingMode.HALF_UP).toDouble res1:Double = 10.23//转换为Double

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中,而不是使用math.Round,您可以使用setScale.

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

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

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