Search code examples
javascalabigdecimal

Scala BigDecimal fails to translate a decimal String representation created by itself


While playing around with generative testing I came across the following:

import org.scalacheck.Properties
import org.scalacheck.Prop.forAll

object BigDecimalSpec extends Properties("BigDecimal") {
  property("apply") = forAll(Arbitrary.arbBigDecimal.arbitrary) {
    x => x == BigDecimal(x.toString())
  }
}

fails with:

! String.apply: Exception raised on property evaluation.
> ARG_0: 0E+2147483648
> Exception: java.lang.NumberFormatException: null
java.math.BigDecimal.<init>(BigDecimal.java:511)
java.math.BigDecimal.<init>(BigDecimal.java:757)
scala.math.BigDecimal$.apply(BigDecimal.scala:119)
scala.math.BigDecimal$.apply(BigDecimal.scala:117)

Why wouldn't BigDecimal be able to translate a decimal String representation created by itself?


Solution

  • This is by definition. From BigDecimal's javadoc:

    The exponent consists of the character 'e' ('\u0065') or 'E' ('\u0045') followed by one or more decimal digits. The value of the exponent must lie between -Integer.MAX_VALUE (Integer.MIN_VALUE+1) and Integer.MAX_VALUE, inclusive.

    Emphasis by me, and Integer.MAX_VALUE = 2147483647.