> Also you should consider making it a habit to always use the
> BigDecimal(String) constructor. That way you wont run into the problem
> with the BigDecimal(Double) constructor. Try just for the fun of it :
> System.out.println(new java.math.BigDecimal(0.1));
> and try to guess the output before running it..;)
The 'problem' with the BigDecimal(double) constructor is generally
overstated. I should know because I've overstated it myself.
The *real* problem with the above is with the conversion of 0.1 to a
double at compile time. Nothing to do with BigDecimal. Try *this*:
System.out.println(new java.math.BigDecimal(Math.pow(2.0,-32.0));
System.out.println(new java.math.BigDecimal(""+Math.pow(2.0,-32.0));
The first line prints the more accurate result. The second line is
entirely and invisibly dependent on rounding that takes place inside
String.valueOf(double) which is not well-specified and which in turn
actually calls Double.toString(double);
Chris Uppal - 13 Sep 2006 09:04 GMT
> [...]
> entirely and invisibly dependent on rounding that takes place inside
> String.valueOf(double) which is not well-specified and which in turn
> actually calls Double.toString(double);
That isn't really true. String.valueOf(double) is documented to be identical
to Double.toString(double), and that latter method is specified quite
carefully. From the JavaDoc:
========
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.
========
which I believe specifies the "rounding" completely.
"Precisely specified" and "does what you want it to do" are, of course, not
necessarily the same...
-- chris
Arne Vajhøj - 13 Sep 2006 17:19 GMT
> The 'problem' with the BigDecimal(double) constructor is generally
> overstated. I should know because I've overstated it myself.
[quoted text clipped - 9 lines]
> String.valueOf(double) which is not well-specified and which in turn
> actually calls Double.toString(double);
That example is rather useless.
The problem is with floating point representation.
BigDecimal(double) does not necessarily match the source code.
BigDecimal(String) do match the source code).
BigDecimal(string expression based on a floating point calculation)
ofcourse has the same floating point problems as the first, but it
is a problem in the expression calculation not in the constructor.
Arne