0

In Android, the value entered into the EditText is converted to float using the following line of code.

        Float addPurchUnitCostPrice = Float.valueOf(addPurchaseCostPrice.getText().toString());

I would like to have the value of addPurchUnitCostPrice with 2 decimal places (always). How can this be done?

user3314337
  • 341
  • 3
  • 13

3 Answers3

2

Floating-point values don't have decimal places. They have binary places, and the two are incommensurable. If you want decimal places you have to use a decimal radix, i.e. BigDecimal.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

You will be better off using the currency formatter in Android, however it requires a double. The currency formatter will also deal with countries that use commas in place of decimal points.

So change your code to

double addPurchUnitCostPrice = Double.parseDouble(addPurchaseCostPrice.getText().toString());
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
String formattedPrice = currencyFormat.format(price);

You will create price with 2 decimal places and format according to the country defined by the users device.

Sanj
  • 850
  • 7
  • 7
  • I changed the format from float to double and used `DecimalFormat df = new DecimalFormat("0.00");`. Working as expected. The decimal values are getting limited to 2 decimal places. Also, the integer values are replaced with two zeros in the place of decimal. However, exploring the **currency formatter** and **Big Decimal**. Thanks everyone for the suggestions – user3314337 Apr 18 '15 at 06:13
0

You can just use BigDecimal for that

shepard23
  • 148
  • 2
  • 13