Domanda

I want to convert a given number according to international number system. // For example:

345678 -> 345,678
12 -> 12 
123 -> 123
4590 -> 4,590

Here is the code snippet and IdeOne link

public static void main (String[] args) throws java.lang.Exception
{
    int number = 345678;
    String s = Integer.toString(number);
    s = putCommas(s);
}

private String putCommas(String s) {
    // How to put commas in string after every 3rd character from right ?
}

Here is my approach with which I am not comfortable.

  1. Start traversing string from right
  2. If the (length - currentIndex -1) % 3 == 0 insert comma in the string

Any suggestions ?

È stato utile?

Soluzione

You can use NumberFormat with Locale#US:

NumberFormat.getNumberInstance(Locale.US).format(number);

Or DecimalFormat:

DecimalFormat formatter = new DecimalFormat("#,###");
String newNumber = formatter.format(number);

Altri suggerimenti

Use the NumberFormat class

http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#getInstance(java.util.Locale)

You can pass it in a Locale and then format the number as required

http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html#format(long)

System.out.println (NumberFormat.getNumberInstance(Locale.US).format(1234567L));

You can use simply NumberFormat class .

NumberFormat numberFormat = NumberFormat.getInstance();
//allows to have number seperated by comma
numberFormat.setGroupingUsed(true);

String formattedNr = numberFormat.format(12345678L);
System.out.println("12345678L number formatted to " + formattedNr);

Output:

12345678L number formatted to 12,345,678.00

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top