2
\$\begingroup\$

The next iteration is here.

I have this small method for printing long integers neatly. For example:

neatify(123L)    = "123"
neatify(1234L)   = "1 234"
neatify(12345L)  = "12 345"
.
.
.

The code:

import java.util.Scanner;

public class Main {

    public static String neatify(final long number,
                                 final int groupLength) {
        final String str = Long.toString(number);

        if (groupLength < 1) {
            return str;
        }

        final char[] charArray = str.toCharArray();
        final StringBuilder sb = new StringBuilder();

        for (int i = 0; i < charArray.length; ++i) {
            if (i != 0 && (charArray.length - i) % groupLength == 0) {
                sb.append(' ');
            }

            sb.append(charArray[i]);
        }

        return sb.toString();
    }

    public static String neatify(final long number) {
        return neatify(number, 3);
    }

    public static void main(final String... args) {
        final Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLong()) {
            System.out.println(neatify(scanner.nextLong()));
        }
    }
}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Usability

  • do you really need the groupLength? I'm not aware of any number writing scheme where it is fixed, but not 3[*].
  • on the other hand, the separator is different in a lot of countries. You can see an example for thousands separators here (or on wikipedia). For example, Canada uses , Italy uses ., the US uses ,, and Switzerland uses '. It might be nice to add that as a parameter instead of hardcoding . You can still use as a default.
  • your code doesn't deal that well with negative numbers. -123 becomes - 123, and -123456 becomes - 123 456. I would not expect a space after the -.

[*] In India it seems to be written eg as 15,00,000, which doesn't use 3, but which also isn't a fixed length.

Misc

  • if you start your loop at 1 and prepend sb.append(charArray[0]);, you can save the i != 0 check you perform each time.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.