如何用Java中的逗号作为千位分隔符打印自然数?

时间:2016-03-01 21:11:59

标签: java

我创建了一个用逗号打印自然数的方法,并且在某种程度上它只在第一千个工作?这是我的代码:

private static void printWithCommas(NaturalNumber n, SimpleWriter out) {
    assert n != null : "Violation of: n1 is not null";
    assert out != null : "Violation of: out is not null";
    assert out.isOpen() : "Violation of: out.is_open";
    NaturalNumber th = new NaturalNumber1L(1000);

    if (n.compareTo(th) < 0) {
        out.print(n);
    }

    else {

        int ones = n.divideBy10();
        int tens = n.divideBy10();
        int hundreds = n.divideBy10();

        out.print(n + "," + hundreds + tens + ones);

    }

}

1 个答案:

答案 0 :(得分:1)

您可以使用 DecimalFormat

实施例

DecimalFormat formatter = (DecimalFormat)  
NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

symbols.setGroupingSeparator(',');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(223423423));