Search code examples
javabigdecimalnumberformatexceptionicedtea

new BigDecimal("0") NumberFormatException


I'm having a weird problem with BigDecimal.

I have a parse method as follows:

protected BigDecimal parseBigDecimalFromText(String text) {
    Logger.info("parseBigDecimalFromText("+text+")");
    return new BigDecimal(text);
}

Now when I run my test the code properly works.

@Test
public void parseBigDecimalFromZero() {
    Logger.createLogger();

    // given
    String text = "0";

    // when
    BigDecimal bigDecimal = basicPage.parseBigDecimalFromText(text);

    // then
    Assert.assertEquals(new BigDecimal("0"), bigDecimal);
}

But when I execute my application passing exactly the same String "0" I got a "java.lang.NumberFormatException"

Following is the log:

2014-11-05 23:21:33.142: INFO - parseBigDecimalFromText(0) 
2014-11-05 23:21:33.142: SEVERE - null 
java.lang.NumberFormatException
    at java.math.BigDecimal.<init>(BigDecimal.java:470)
    at java.math.BigDecimal.<init>(BigDecimal.java:739)
    at com.aa.travian.pages.BasicPage.parseBigDecimalFromText(BasicPage.java:121)

I know that when my app starts I'm setting a specific Locale:

Locale locale = getConfig().getLocale();
ResourceBundle = ResourceBundle.getBundle("translations", locale);

but I don't see how this should break my parseBigDecimalFromText method.

Following is my java version:

java -versionjava version "1.7.0_65"
OpenJDK Runtime Environment (IcedTea 2.5.2) (7u65-2.5.2-3~14.04)
OpenJDK 64-Bit Server VM (build 24.65-b04, mixed mode)

Any idea what is happening here? Looking at the BigDecimal source code it looks like it falls while parsing the exponent:

// exponent expected
if ((c != 'e') && (c != 'E'))
    throw new NumberFormatException();

Thanks in advance for your time.


Solution

  • You can't log a string variable to verify its contents, because many many different strings are not visually distinguishable.

    Instead, treat all your strings as binary data. Make a hex dump and compare that.

    Here's one way of reproducing your output and problem:

    $ cat Test.java
    import java.util.regex.*;
    import java.util.logging.*;
    import java.math.*;
    
    class Test {
        public static void main(String[] args) {
            Logger logger = Logger.getLogger("test");
            String text = "0\0";
            logger.info("parseBigDecimalFromText("+text+")");
            new BigDecimal(text);
        }
    }
    
    $ javac Test.java
    $ java Test
    Nov 06, 2014 12:55:40 AM Test main
    INFO: parseBigDecimalFromText(0)
    Exception in thread "main" java.lang.NumberFormatException
            at java.math.BigDecimal.<init>(BigDecimal.java:470)
            at java.math.BigDecimal.<init>(BigDecimal.java:739)
            at Test.main(Test.java:10)
    $