Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

floating point - Round a double in Java

I have found this great solution for rounding:

static Double round(Double d, int precise) {
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(precise, RoundingMode.HALF_UP);
    return bigDecimal.doubleValue();
}

However, the results are confusing:

System.out.println(round(2.655d,2)); // -> 2.65
System.out.println(round(1.655d,2)); // -> 1.66

Why is it giving this output? I'm using jre 1.7.0_45.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to replace

BigDecimal bigDecimal = new BigDecimal(d);

with

BigDecimal bigDecimal = BigDecimal.valueOf(d);

and you will get the expected results:

2.66
1.66

Explanation from Java API:

BigDecimal.valueOf(double val) - uses the double's canonical string representation provided by the Double.toString() method. This is preferred way to convert a double (or float) into a BigDecimal.

new BigDecimal(double val) - uses the exact decimal representation of the double's binary floating-point value and thus results of this constructor can be somewhat unpredictable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...