bscouth
bscouth

Reputation: 9

How to print natural number with comma as thousand separator in Java?

I create a method that will print natural number with comma and in somehow it's only work at the first thousand? here is my code:

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

    }

}

Upvotes: 0

Views: 1251

Answers (1)

You can use DecimalFormat class

Example:

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

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

Upvotes: 1

Related Questions