繁体   English   中英

DecimalFormat 解析数字错误。 为什么?

[英]DecimalFormat is parsing number wrong. Why?

我目前创建了一个基本的 Java 应用程序,它允许将提供的数字解析为格式化的字符串。
我现在面临的问题是,DecimalFormat 以错误的格式格式化提供的值。

例子:

private final DecimalFormat format = new DecimalFormat();

public static void main(String[] args){
    int number;
    try{
        number = Integer.parseInt(args[0]);
    }catch(NumberFormatException ex){
        System.out.println("The provided value was invalid!");
        System.exit(0);
        return;
    }

    format.applyPattern("#,###,###.##");

    return format.format(number);
    System.exit(0);
}

我在这里面临的问题是,例如,如果我提供数字123456789作为 jar 命令中的第一个参数,它会返回123'456'789而不是123,456,789的期望结果。

什么可能导致这个问题?

使用java.text.DecimalFormat导入,以及此代码:

private static final DecimalFormat format = new DecimalFormat();

    public static void main(String[] args) {
        int number = 1456781;

        format.applyPattern("#,###,###.##");

        System.out.println("The formatted version is -> " + format.format(number));
    }

我得到的 output 是

The formatted version is -> 1,456,781

Process finished with exit code 0

所以它似乎正确格式化它?

我在这里看到的一个问题是,您返回的是Integer而不是 void 。 此外,您正在从 static function 访问非静态 function format 您可以将其移动到 function 中,或用作 static 变量。

private static DecimalFormat format = new DecimalFormat();

public static void main(String[] args){
    int number;
    try{
        number = Integer.parseInt(args[0]);
    }catch(NumberFormatException ex){
        System.out.println("The provided value was invalid!");
        System.exit(0);
        return;
    }

    format.applyPattern("#,###,###.##");

    System.out.println(format.format(number));
    System.exit(0);
}

如果上述方法不起作用,则很有可能它来自您的语言环境。 您可以使用此答案强制语言环境

暂无
暂无

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

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