开发者

In Java, how would I round a number to an arbitrary level of precision?

For example suppose I have a method

double roundDown(double unrounded, double precision) {
}

roundDown(137.42973, 开发者_JAVA技巧0.01) would return 137.42
roundDown(137.42973, 0.05) would return 137.4
roundDown(137.42973, 0.25) would return 137.25

Are there libraries to do something like this otherwise is the algorithm reasonably simple?


Divide the original number by the precision, round down to the nearest integer, and then multiply by the precision again:

double roundDown(double unrounded, double precision) {
    return precision * Math.floor(unrounded / precision);
}

Note that inherent floating point inaccuracies mean that your number may not be exactly the answer you're looking for - e.g. you might get 137.399999 instead of 137.4


If you want truly arbitrary precision in decimal, look into this library: http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigDecimal.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜