About rounding issues in Java

What needs to be done when we have a decimal such as 0.415/0.425 that needs to be rounded to n (here 3) digits?

 

There is a Math.round method in Java. When the input is 12.5, the result is 13. When the input is -12.5, the result is -12. If you want to round off the significant digits in the decimal point, you can use the input decimal *Math.pow(10, n-1)+0.5, then enter Math.round and divide back to Math.pow(10, n-1) , here is 0.415/0.425 * 100 + 0.5 = 41.5/42.5, Then Math.round(41.5/42.5) * 100 = 0.42/0.43

 

In addition to this general rounding, there are various rounding versions in other places such as finance, which are not recorded here for the time being.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689432&siteId=291194637