I'm using a button to calculate discounts when the user input the discount rate to the app. When I get a Total Value below 1000 it is working fine and gives the discount. But if the total value is greater than 1000, it gives the Fatal Exception and crashes the app. Can you help me to fix this issue? Thank you
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Double discountRate = Double.parseDouble(input_rate.getText().toString());
Double discount = 0.0;
if(discountRate.equals("")){
Toast.makeText(CreateInvoiceActivity.this, "Discount Rate is Empty", Toast.LENGTH_SHORT).show();
}
else {
Double totalValue = Double.parseDouble(invoiceTotal.getText().toString());
try {
discount = (totalValue * (discountRate / 100));
Toast.makeText(CreateInvoiceActivity.this, "Discount is" discount, Toast.LENGTH_SHORT).show();
}catch (NumberFormatException ignore){}
}
}
});
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antlergroup.aits.ierunt.ai, PID: 26795
java.lang.NumberFormatException: For input string: "1,008.00"
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
at java.lang.Double.parseDouble(Double.java:547)
at com.antlergroup.aits.ierunt.ai.view.activity.CreateInvoiceActivity$2.onClick(CreateInvoiceActivity.java:291)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22479)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6623)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
I/Process: Sending signal. PID: 26795 SIG: 9
CodePudding user response:
You should remove the thousands separator (comma).
Double totalValue = Double.parseDouble(invoiceTotal.getText().toString().replace(",", ""));
You should also:
- Prefer java.text.NumberFormat to parse the number
- Use the correct locale
- Validate the input