简体   繁体   English

尝试在 Java 中将字符串值转换为 Double 时出现异常

[英]Exception while trying to convert String value to Double in Java

I am getting the below error when trying to convert string to double.尝试将字符串转换为双精度时出现以下错误。

For input string: "1,514,230.15"

Exception:
java.lang.NumberFormatException: For input string: "1,514,230.15"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)

This is the line of code I am using这是我正在使用的代码行

 testString = "1,514,230.15"
 double d= Double.parseDouble(TestString);

Can someone help me understand what I am doing wrong here?有人可以帮我理解我在这里做错了什么吗?

Solution 1:解决方案1:

String testString = "1,514,230.15".replace(",", "");
double d = Double.parseDouble(testString);
System.out.println(d);

Or Solution 2:或解决方案2:

String input = "1,514,230.15";
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
double result = numberFormat.parse(input).doubleValue();
System.out.println(result);

Or Solution 3:或解决方案 3:

String testString = "1514230.15";
double d= Double.parseDouble(testString);
System.out.println(d);

Output: Output:

1514230.15

Explanation:解释:

  1. In solution 1 used replace method to replace all , ie replace(",", ""); solution 1中使用replace方法替换all ,replace(",", "");
  2. In solution 2 used NumberFormat .solution 2中使用了 NumberFormat This class provides the interface for formatting and parsing numbers.这个 class 提供了格式化和解析数字的接口。
  3. In solution 3 removed all , from testString ie String testString = "1514230.15";solution 3中删除了所有,testStringString testString = "1514230.15";

You should use NumberFormat#prase which is specialized for such conversions.您应该使用专门用于此类转换的NumberFormat#prase Your input string complies with the number format for Locale.US .您的输入字符串符合Locale.US的数字格式。

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        String input = "1,514,230.15";
        NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
        double n = numberFormat.parse(input).doubleValue();
        System.out.println(n);
    }
}

Output: Output:

1514230.15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM