当我有双精度格式时如何解析整数?

How to parse an integer, when I have a format for a double?

我正在从我的数据库中获取用户条目,该数据库存储用户输入的值,可能是 float 或 int,但我的代码旨在检查以下条件

String pattern = "###,###.##";
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
if (!userput.equals("")){
        resultoutput.setText(""+Double.parseDouble(userput)*Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));}
        else{
            userinput.setText("1");
            resultoutput.setText(""+Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));
        }

所以遇到int就崩溃了。例如,对于 13152,它给出 java.lang.NumberFormatException: Invalid double: "13,152"

此外,如果我得到这样的输出 13170.00 我会得到如下错误 java.lang.NumberFormatException: Invalid double: "13,170.00"

从数据库中取出的值有时包含浮点数有时包含整数,这里x[1]是货币汇率,userinput包含integerfloat... .假设我正在尝试获取 usd to idr currency 所以我得到 13170.00 而不是 double 也不是 int 因为我收到此错误 java.lang.NumberFormatException: Invalid double: "13,170.00"

double,因为它包含.,不包含fF后缀。

来自Java Tutorials

The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).

double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1  = 123.4f;

您的问题不在于数字是整数还是双精度。你的问题出在你的转化率超过三位数。

这是您显示值的代码(重新格式化):

resultoutput.setText(
    ""
    + Double.parseDouble(userput)
    * Double.parseDouble(decimalFormat.format(Double.parseDouble(x[1]))));

那么,你是:

  1. 获取您的汇率,这是一个字符串,并将其转换为双精度。
  2. 获取生成的双精度值,并使用十进制格式将其转换回字符串。
  3. 获取格式化文本,并将其再次转换为双精度
  4. 将其乘以用户输入的双精度值
  5. 正在将结果转换为字符串(不带格式)。

问题出在第2步和第3步,其实是不需要的。但对于某些数字,它们会起作用。

您的格式是###,###.##。让我们看看一些数字用这种格式格式化后的样子:

╔═════════╤═══════════╗
║ number  │ formatted ║
╠═════════╪═══════════╣
║ 0.273   │ 0.27      ║
╟─────────┼───────────╢
║ 5.3     │ 5.3       ║
╟─────────┼───────────╢
║ 358.2   │ 358.2     ║
╟─────────┼───────────╢
║ 10.0    │ 10        ║
╟─────────┼───────────╢
║ 1298.52 │ 1,298.52  ║
╚═════════╧═══════════╝

因此,当您的转换率小于小数点左侧四位时,decimalFormat.format() 调用会将它们转换为仍然合法的 Java 双精度字符串。因此,当您随后在步骤 3 中对该字符串调用 Double.parseDouble 时,一切正常。

但是当你的数字很大时,比如"13152.00",你要做的是:

  1. 将其转换为双精度:13152.0
  2. 将其转换为格式为字符串:13,152.0
  3. 将其转换为双精度:- 这不起作用。 Java 在 Double.parseDouble() 的输入中不接受 ,

所以说真的,你的转换应该只是:

resultoutput.setText(
    ""
    + Double.parseDouble(userput)
    * Double.parseDouble(x[1]));

这会在 resultoutput 中为您提供一个正确的、未格式化的数字,而不会引发异常。

我很确定您想要 decimalFormat 是为了显示数字,而不是为了一次又一次地转换它。这意味着你应该只在转换结果上使用它——而不是做 "" + ...,它只给你默认格式。

resultoutput.setText(
    decimalFormat.format( Double.parseDouble(userput) * Double.parseDouble(x[1])));

请注意,您不会在您的格式中看到小数点后的两位数字 - 它将 10.0 显示为 10。如果您想始终显示两位数,则必须使用 ###,##0.00 作为您的格式。