2

i do the below java print command for this double variable double test=58.15; When i do a System.out.println(test); and System.out.println(new Double(test).toString()); It prints as 58.15.

When i do a System.out.println(new BigDecimal(test)) I get the below value 58.14999999999999857891452847979962825775146484375

I am able to understand "test" double variable value is internally stored as 58.1499999. But when i do the below two System.out.println i am getting the output as 58.15 and not 58.1499999.

System.out.println(test);

System.out.println(new Double(test).toString());

It prints the output as 58.15 for the above two.

Is the above System.out.println statements are doing some rounding of the value 58.1499999 and printing it as 58.15?

4

3 回答 3

5
System.out.println(new BigDecimal("58.15"));

To construct a BigDecimal from a hard-coded constant, you must always use one of constants in the class (ZERO, ONE, or TEN) or one of the string constructors. The reason is that one you put the value in a double, you've already lost precision that can never be regained.

EDIT: polygenelubricants is right. Specifically, you're using Double.toString or equivalent. To quote from there:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

于 2010-03-09T02:18:41.883 回答
3

Yes, println (or more precisely, Double.toString) rounds. For proof, System.out.println(.1D); prints 0.1, which is impossible to represent in binary.

Also, when using BigDecimal, don't use the double constructor, because that would attempt to precisely represent an imprecise value. Use the String constructor instead.

于 2010-03-09T02:19:59.770 回答
1

out.printlnDouble.toString()使用Double.toString(double)中指定的格式。

BigDecimal 默认使用更高的精度,如javadoc中所述,当您调用toString()它时,会输出所有字符,直到原始 double 可用的精度级别,因为 .15 没有精确的二进制表示。

于 2010-03-09T02:20:51.017 回答