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

1 Answer

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

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

    Architecture notes:
    -------------------
    - Kotlin uses Java's formatting classes under the hood.
    - 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
*/


// Create a reusable formatter with space as thousands separator
private val formatter: DecimalFormat = run {
    val symbols = DecimalFormatSymbols().apply {
        groupingSeparator = ' '   // use space instead of comma
    }

    DecimalFormat("#,###", symbols).apply {
        groupingSize = 3          // group digits in threes
    }
}


// Format a long value using the custom formatter
fun formatWithSpaces(value: Long): String {
    return try {
        formatter.format(value)
    } catch (ex: Exception) {
        "unformatted (error: ${ex.message})"
    }
}


fun main() {
    val tests: Array<Long> = arrayOf(
        0,
        42,
        1234,
        987_654_321,
        -1_234_567,
        1_000_000_000_000_000_000L   // 10^18
    )

    println("Running test cases:\n")

    for (n in tests) {
        println("Original:  $n")
        println("Formatted: ${formatWithSpaces(n)}")
        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
...