Java.lang.NumberFormatException: for input line: "20,475.00"
I am trying to get the current balance of my system. To do this, I get the sum of all numbers in the jtable from the AMOUNT column 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 am getting the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20,475.00"
How can I solve this? any help would be appreciated. Thanks to
source to share
Since Float.parseFloat () and Float.valueOf () will always assume that the number is in your local format, here's a quick example of how to do localized parsing if your language doesn't match the format of the number you receive.
String str = "20,475.00";
NumberFormat nf = NumberFormat.getInstance(Locale.US); // Looks like a US format
float f = nf.parse(str).floatValue();
source to share
Use NumberFormat
class instead of Float.parseFloat
. This will allow you to specify the format for parsing the formatted number, eg 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());
source to share
Your number depends on the language. A normal number can only contain an optional leading minus sign and an optional decimal point. Comma-separated numbers are not supported.
The NumberFormat class, as suggested by Pablo Santa Cruz, allows you to specify your own number formatting and parsing according to that format.
If you are going to use decimals I can suggest using DecimalFormat
source to share