Search code examples
javastringjtablebigdecimalnumberformatexception

String value from a JTable to BigDecimal throws Java.lang.NumberFormatException


I am making a graphing calculator that allows the calculation of data with errors (i.e. 5 +-0.02). I have created an object named Numbers3 which in its attributes has a BigDecimal variable. When I input the data trough the console, everything works fine. The problem comes when I am trying to retreive the data from a JTable; I convert the object to String, but when it faces BigDecimal(String) it throws an exception:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException
    at java.math.BigDecimal.<init>(BigDecimal.java:470)
    at java.math.BigDecimal.<init>(BigDecimal.java:739)

This is how I am getting the object from a JTable to a String. This is working because when I print the return from .getClass() the output is java.lang.String):

String number = (String)(table.getValueAt(i,j));

Have also tried several other options, such as:

String number=new String(String.valueOf(table.getValueAt(i,j));

I would really appreciate any help with this problem.


Solution

  • Try to normalize string to fit BigDecimal requirements:

    private static BigDecimal parse(String str) {
        String normalized = str.replaceAll("\\s", "").replace(',', '.');
        return new BigDecimal(normalized);
    }
    

    Above code removes all whitespace characters from input string (which are not allowed in BigDecimal constructor).

    What is more - it replaces comma to decimal point if needed.