Rounding to 2 decimal places in mongodb

2019-02-26 09:08发布

问题:

I have my collection as

Student

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

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.

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.

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; 
    }
}) 

回答1:

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> 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 // Rouding Off

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