Reputation: 341
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?
Upvotes: 0
Views: 592
Reputation: 850
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.
Upvotes: 0
Reputation: 310957
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.
Upvotes: 2