-3
public class test
{
    public static void main(String[] args)
    {
        String abra = "100000";
        abra = abra.replace(abra.substring(abra.length() - 3),
               "," + abra.substring(abra.length() - 3));
        System.out.println(abra);
     }
}

Totally new to java and i'm trying to replace a number with comma to separate the zeros by three. It works fine for thousands and ten thousands, but i'm getting wierd results for more. Any ideas?

Thanks in advance!

Thomas
  • 177
  • 8

1 Answers1

3

Because you're manually only for 6 digits. A better approach will be using NumberFormat#getNumberInstance with Locale.US:

A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation— the number should be formatted according to the customs and conventions of the user's native country, region, or culture.


NumberFormat.getNumberInstance(Locale.US).format(20000000);
// 20,000,000
Maroun
  • 94,125
  • 30
  • 188
  • 241