Best method to round up to the nearest 0.05 in java

前端 未结 3 455
太阳男子
太阳男子 2020-12-06 19:42

Consider that a tax of 10% is applicable on all items except food. Also, an additional tax of of 5 % is applicable on imported items.

If the cost of a music CD is

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 19:57

    This seems to be part of a famous tech interview problem The point is to understand that you have to calculate the taxes and round that amount to the upper 0.05 to calculate the rounding i used this groovy script

    import java.math.*
    
    def myRound(BigDecimal d){ 
        def scale = new BigDecimal("0.05")
        def y = d.divide(scale)
        println "y :$y"
    //    def q = y.round(new MathContext(0,RoundingMode.UP))
        def q = y.setScale(0,BigDecimal.ROUND_UP)
        println "q :$q (intero)"
        def z = q.multiply(scale)
        println "z :$z"
        return z
    }
    
    def taxBy(BigDecimal d,BigDecimal t){ 
        return myRound(d.multiply(t))
    }
    def importTax(BigDecimal d){ 
        return taxBy(d,new BigDecimal("0.15"))
    }
    
    def importBaseTax(BigDecimal b){ 
        return taxBy(d,new BigDecimal("0.05"))
    }
    
    ip = new BigDecimal("27.99")
    ipt = importTax(ip)
    
    println "${ip}-->${ipt} = ${ip+ipt}"
    

    I hope this to be useful!

提交回复
热议问题