Java 将字符串解析为双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6426491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:49:27  来源:igfitidea点击:

Parsing String to Double

java

提问by Kevin W

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.

我正在尝试将 String 解析为 Double,但我不确定这是否是正确的方法。如果有人可以帮助我检查它并提供反馈,我将不胜感激。

Here's the code:

这是代码:

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

Thank you in advance for your kind comments.

预先感谢您的友好评论。

回答by Nathan Romano

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

回答by Greg Reynolds

You could try

你可以试试

double subtotal = Double.parseDouble(amount);

回答by Xion

You should wrap this call around a try-catchblock and handle NumberFormatExceptionwhich will be thrown if the string cannot be parsed as Double.

您应该将此调用包装在一个try-catch块和句柄周围NumberFormatException,如果无法将字符串解析为Double.

回答by Chirag

You can also try this.

你也可以试试这个。

double subtotal = Double.parseDouble(amount);

回答by Martijn Courteaux

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

我所做的是(使用 aJFormattedTextField或 a 时JTextField)用点替换所有逗号并删除空格:

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 (/)

蓝色 = 点;
绿色 = 逗号;
红色 = 莫马耶兹 (/)

回答by Thomas Johansson

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.

在您的情况下,您必须将 Integer.parseInt() 函数更改为您想要的任何类型。

回答by Rostislav Matl

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

如果你想成为国际化的,你应该使用这个:

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