Best method to round up to the nearest 0.05 in java

落花浮王杯 提交于 2019-11-28 02:03:35

You can use long instead of double to use double you can do

double d = Math.round(d * 20) / 20.0; // round up to multiple of 0.05

to use long (as cents)

long l = (l + 3) / 5 * 5;

Although its often considered best practice to use int, long or BigDecimal most investment banks and funds use double because once you understand how to use them safely, they are simpler (than long) and faster (than BigDecimal) to use.

John3136

Store monetary amounts as integers (e.g. a number of cents).

This is a common issue - google will give you plenty of great explanations.

Here is one: Why not use Double or Float to represent currency?

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!