开发者

Parsing String to Double [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Existing String to Double

开发者_运维技巧

I'm trying to parse String into Double, and I'm not sure if it is the correct way to do it. If anyone can help me check on it, and give feedback I'd really appreciate it.

Here's the code:

    String amount = enterAmount.getText().toString();
    double subtotal = Double.valueOf(amount).doubleValue();

Thank you in advance for your kind comments.


You could try

double subtotal = Double.parseDouble(amount);


String amount = enterAmount.getText();
double subtotal = Double.parseDouble(amount);


You should wrap this call around a try-catch block and handle NumberFormatException which will be thrown if the string cannot be parsed as Double.


You can also try this.

double subtotal = Double.parseDouble(amount);


What I do, is (when using a JFormattedTextField or a JTextField) replacing all the comma's by points and removing the spaces:

String amount = enterAmount.getText();
amount = amount.replace(",",".").replace(" ", "");
double subtotal = Double.parseDouble(amount);

This means following input will work:

12
1,2
1.2
200 000
200 000,01

The commas are used in a lot of European countries: Wikipedia

Blue = point;
Green = comma;
Red = Momayyez (/)


You should use some logic to determine if it is a valid number. Here is a function for testing integers:

public static int validateInteger(String number)
{
  int i = -1;

  try {
  i = Integer.parseInt(number);
  }
  catch (NumberFormatException nfe)
  {}
  catch (NullPointerException npe)
  {}

  return i;
}

In your case, you have to change the Integer.parseInt() function into whatever type you want.


If you want to be international, you should probably use this:

DecimalFormat.getNumberInstance(Locale).parse(numberAsString).doubleValue()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜