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

我目前正在创建一个基本的Java应用程序,该应用程序可以将提供的数字解析为格式化的String。 我现在面临的问题是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);
}

The issue I face here is, that if I, for example, provide the number 123456789 as the first argument in the jar command, will it return 123'456'789 and not the desired result of 123,456,789.

是什么导致此问题?

评论
cet
cet

What I can see as an issue here is that you are returning Integer instead of void in the return. Also, you are accessing non-static function format from a static function. You can move this inside your function, or use as a static variable.

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);
}

If the above doesn't work, there's a good chance it's coming from your locale. You can force locale using this answer

点赞
评论
dquia
dquia

With the java.text.DecimalFormat import, and this code:

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));
    }

我得到的输出是

The formatted version is -> 1,456,781

Process finished with exit code 0

看来格式正确吗?

点赞
评论