3

I am using the following code where k is a BigDecimal:

Apfloat power = ApfloatMath.pow(new Apfloat(-1), new Apfloat(k));

Apfloat seems to have methods like intValue(), doubleValue(), floatValue() but I can't see how I can convert Apfloat to BigDecimal.

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
user2948708
  • 115
  • 1
  • 1
  • 5
  • Oh I forgot to mention the docs are at: http://www.apfloat.org/apfloat_java/docs/org/apfloat/Apfloat.html – user2948708 Nov 02 '13 at 23:35
  • The only trivial way of doing this I can find is converting the `Apfloat` to a string (since it is `Formattable`) and then constructing a new `BigDecimal` from that string. Dunno if the string you get is usable, though. –  Nov 02 '13 at 23:35

1 Answers1

2

BigDecimals are best generated from Strings or using the BigDecimal.valueOf( double) static constructor.

For your specific requirement, start with the following:

public static asBigDecimal (Apfloat val) {
    return BigDecimal.valueOf( val.doubleValue());
}

Calling new BigDecimal(double) is specifically to be avoided, since it generates exact decimal representations of the floating-point bits & can somewhat unpredictably require vast numbers of decimal digits to do so.

On the other hand, BigDecimal.valueOf( double) and Double.toString( double) have specific logic to represent doubles -> decimal without spurious deep decimalization.

See:

  • java.math.BigDecimal.BigDecimal(double)

Quoting from the Javadoc:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

Thomas W
  • 13,940
  • 4
  • 58
  • 76