1

I would like to format large numbers with an underscore as separator. I had hoped that String.format or DecimalFormat could be used. Example:

int number = 1234567;
String str1 = String.format("%,d", number);
System.out.println(str1);  // out puts  1,234,567

but changing comma with underscore

String str = String.format("%_d", number);

causes an exception

UnknownFormatConversionException: Conversion = '_'

DecimalFormat decimalFormat = new DecimalFormat("#_###");
String str2 = decimalFormat.format(number);
System.out.println(str2); // out puts 1234567_

Desired out put 1_234_567

nopens
  • 721
  • 1
  • 4
  • 20
  • 1. Format the number as a string with a comma separator. 2. Replace ',' with '_'. – rossum Aug 13 '19 at 18:11
  • @rossum How stupid of me not to think of it myself. Get it working with `String.format("%,d", number).replace('.', '_')` – nopens Aug 13 '19 at 18:16

1 Answers1

1

You can use DecimalFormat. See the documentation for more information. You have to set the separator to "_" on your formatter object. For example:

    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator('_');
    symbols.setGroupingUsed(true);

    DecimalFormat df = new DecimalFormat("#######", symbols);
    df.setGroupingSize(3);

    String out = df.format(1234567);
geco17
  • 5,152
  • 3
  • 21
  • 38
  • Thank you very much. This is indeed the right answer i was looking for, as i was wanting to apply a strange format to a number and the answers in the "duplicate" did not cover my issue. With `symbols.setGroupingSeparator('_'); symbols.setDecimalSeparator('|'); ` and `new DecimalFormat("####,###.##", symbols);` now i am able to output something like `12_345|67` for the input of `12345.67` – nopens Aug 13 '19 at 18:37