Frage

I can't seem to get my head around this. If have tried the following approaches:

DecimalFormat df = new DecimalFormat("00000.00");

DecimalFormat df = new DecimalFormat("######.##");

But the following line always generates and IllegalArgumentException.

double price = Double.valueOf(df.format(((EditText) view
                .findViewById(R.id.edit_item_price)).getText().toString()));
// Sample input passed is value of 200 or some other whole number.
item.setPrice(price);

It doesn't make sense as I only copied the obvious solutions in this forum. Most of you got the format() to work.

Originally, I didn't have these lines of code. I just call my setPrice() method after getting the item price. This works. However, Double.valueOf() has a nasty habit of using only one decimal position.

e.g. passed 200. I get 200.0 inside my item object. I figured by using DecimalFormat I could've prevented this but it appears this caused me MORE headaches instead.

War es hilfreich?

Lösung

When you say you pass 200 and you get 200.0, you mean you get it in a double value? If so, that doesn't matter - it's a number and 200 = 200.0 for double values.

Andere Tipps

format(...) turns a double value to a String value. You have it the other way round. That's why you get the Exception.

If the price variable is actually a double you should do

double price = Double.valueOf(((EditText) view .findViewById(R.id.edit_item_price)).getText().toString())

But I think you want that the price is a String, then you should convert the text from the EditText to a double and that double back to a String with something like new DecimalFormat("0.00")

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top