5

Hello I would like to use DecimalFormat to display:

8392472 as

839 24 72

I have tried

DecimalFormat dc = new DecimalFormat("000 00 00");
return dc.format(number);

I have also tried "### ## ##"

Yoda
  • 17,363
  • 67
  • 204
  • 344

3 Answers3

1

I don't think you can do that with a DecimalFormat because your spaces are not group or decimal separators.

The simple way would be to simply use a string:

int number = 8392472;
String s = String.valueOf(number);
String formatted = s.substring(0, 3) + " " 
                 + s.substring(3, 5) + " "
                 + s.substring(5, 7);
assylias
  • 321,522
  • 82
  • 660
  • 783
0

I think easiest way to achieve this is as below.

public static void main(String[] args) {
    int number = 8392472;
    StringBuilder sb = new StringBuilder(String.valueOf(number))
                                .insert(3," ")
                                .insert(6," ");
    System.out.println(sb.toString());    
}
Tushar Trivedi
  • 400
  • 1
  • 2
  • 12
  • This is slightly less efficient as it will involve copying the underlying array twice - that will probably not make a noticeable difference in most cases. – assylias Apr 15 '13 at 13:33
  • Any phone number with leading 0's will mess up. Used to be, in the US and Canada, all area codes began with the digit 2-9 and had 0 or 1 as the 2nd digit. The 2nd digit part isn't true any more. I don't know if the first digit can be 0 now. – Lee Meador Jun 24 '13 at 20:41
-1

Use the library of Google! It works well for us.

https://code.google.com/p/libphonenumber/

jelgh
  • 705
  • 1
  • 6
  • 22