Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NumberFormatException: For input string: "20,475.00"

i am trying to get the running balance of my system. To do it, i get the sum of all numbers in the jtable from column AMOUNT and subtract the sum to the value inside the txtLoanAmount. here's my code snippet:

String LoanAmount = txtLoanAmount.getText();
float f = Float.valueOf(LoanAmount.trim()).floatValue();
float balance = 0; 
float sum = 0;

for(int i=0;i<=tableLedger.getRowCount()-1;i++) {
    sum = sum + Float.parseFloat(tableLedger.getModel().getValueAt(i, 2).toString());
}
balance = f - sum;
System.out.println(balance);

now i get the error message :

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20,475.00"

How can i solve this ? any help will be appreciated. Thanks

like image 295
zairahCS Avatar asked Mar 11 '12 15:03

zairahCS


3 Answers

Since Float.parseFloat() and Float.valueOf() always will assume that the number is in your local format, here's a short example how to do localized parsing if your locale does not match the number format you're getting.

String str = "20,475.00";
NumberFormat nf = NumberFormat.getInstance(Locale.US); // Looks like a US format
float f = nf.parse(str).floatValue();
like image 174
Joachim Isaksson Avatar answered Sep 24 '22 04:09

Joachim Isaksson


Use NumberFormat class instead of Float.parseFloat. It will allow you to specify a format for parsing a formatted number such as 20,475.00.

Example:

NumberFormat nf = NumberFormat.getInstance();
// provided your Locale information matches your number format
sum += nf.parse(tableLedger.getModel().getValueAt(i, 2).toString());
like image 20
Pablo Santa Cruz Avatar answered Sep 23 '22 04:09

Pablo Santa Cruz


Your number is locale-dependent. Normaly a number can only contain optional minus sign at the beginning and optional decimal dot. Comma-separated thousands are not supported.

NumberFormat class, as Pablo Santa Cruz suggested, allows you to specify your own format of numbers and parse according to that format.

If you are going to use decimals, I can suggest using DecimalFormat

like image 41
Jakub Zaverka Avatar answered Sep 24 '22 04:09

Jakub Zaverka