Search code examples
androidnumber-formattingdecimal-point

android app adding a price = 1,000 returns total_sum = 1


I have an android app that takes prices and quantities from EditTexts and calculates sum1 = quantity_1 * price_1 etc. total = sum1 + sum2 etc. Calculation is correct when i do something like 1.1 + 1.1 = 2.2 !CORRECT! When i add 1 + 1,000 (one thousand) then it gives me total = 2 !WRONG! it should be total = 1,001.

(i tried 1 + 1000.00 but still editText takes value of 1,000 and problem remains) . is decimal point and ,(comma) is grouping

my sqlite database

  • KEY_PRICE + " INTEGER,"

getting sum

public String getSum() {

    String sumresult = null;
    SQLiteDatabase database = this.getReadableDatabase();
    String selectQuery = "SELECT SUM(price) FROM price_table WHERE etc etc;
    Cursor cursor = database.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
      do {
        sumresult = cursor.getString(0);
      } while (cursor.moveToNext());
    }           
    return sumresult;
  }

and how the calculation is made

    quantity_1=Float.parseFloat(edittext_quantity_1.getText().toString());
    price_1=Float.parseFloat(edittext_price_1.getText().toString());
    sum1=quantity_1*price_1;

//etc for sum2

total= sum1 + sum2;
DecimalFormat df = new DecimalFormat("####.##"); 
total = Float.valueOf(df.format(total));
NumberFormat formatter = NumberFormat.getInstance(Locale.US);       
edittext_total_price.setText(formatter.format(total));

Thanks in advance for your effort.


Solution

  • The Float.parseFloat method ignores everything after (and including) the comma. You have to remove the commas first:

    quantity_1=Float.parseFloat(edittext_quantity_1.getText().toString().replace(",", ""));
    price_1=Float.parseFloat(edittext_price_1.getText().toString().replace(",", ""));