user3314337
user3314337

Reputation: 341

Float value with 2 decimal places

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

Answers (3)

shepard23
shepard23

Reputation: 188

You can just use BigDecimal for that

Upvotes: 0

Sanj
Sanj

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

user207421
user207421

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

Related Questions