Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to print a number with a thousand separator as spaces in Java

1 Answer

0 votes
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

/**
    Program: Print numbers with a thousand separator as spaces in Java.

    Architecture notes:
    -------------------
    - Java's DecimalFormat allows customizing:
        * grouping separator (thousands separator)
        * grouping size
    - We configure DecimalFormatSymbols to use a space (' ') as the separator.
    - The formatter is reused for all numbers to avoid repeated allocations.

    Performance notes:
    ------------------
    - Formatting is O(n) in the number of digits.
    - DecimalFormat is efficient and safe for repeated use.
    - Memory usage is minimal; only small strings are created.

    Pitfalls:
    ---------
    - DecimalFormat is not thread-safe; avoid sharing across threads without care.
    - Negative numbers must preserve the minus sign; DecimalFormat handles this.
    - Very large numbers (BigInteger) require converting to string first.

    Security notes:
    ---------------
    - No external input parsing; safe for demonstration.
    - Avoid printing sensitive values in real systems.

    Tests:
    ------
    - Positive numbers
    - Negative numbers
    - Zero
    - Very large integers
*/


public class ThousandSeparatorSpaces {

    // Create a reusable formatter with space as thousands separator
    private static final DecimalFormat formatter;

    static {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        symbols.setGroupingSeparator(' ');   // use space instead of comma

        formatter = new DecimalFormat("#,###", symbols);
        formatter.setGroupingSize(3);        // group digits in threes
    }

    // Format a long value using the custom formatter
    public static String formatWithSpaces(long value) {
        try {
            return formatter.format(value);
        } catch (Exception ex) {
            return "unformatted (error: " + ex.getMessage() + ")";
        }
    }

    public static void main(String[] args) {
        long[] tests = {
            0,
            42,
            1234,
            987_654_321L,
            -1_234_567L,
            1_000_000_000_000_000_000L   // 10^18
        };

        System.out.println("Running test cases:\n");

        for (long n : tests) {
            System.out.println("Original:  " + n);
            System.out.println("Formatted: " + formatWithSpaces(n));
            System.out.println();
        }
    }
}


/*
run:

Running test cases:

Original:  0
Formatted: 0

Original:  42
Formatted: 42

Original:  1234
Formatted: 1 234

Original:  987654321
Formatted: 987 654 321

Original:  -1234567
Formatted: -1 234 567

Original:  1000000000000000000
Formatted: 1 000 000 000 000 000 000

*/

 



answered Sep 22 by avibootz
...