How to format every 3 digits of a number into comma-separated digits in Java

How to format every 3 digits of a number into comma-separated digits in Java

DecimalFormat class is used to format numbers.

import java.text.DecimalFormat;

public class DecimalFormatSample2 {
  public static void main(String[] args) {
    final DecimalFormat decFormat = new DecimalFormat("###,###");
    final String str = decFormat.format(1230000000);
    System.out.println(str); // 1,230,000,000
  }
}

decimal fraction

If you want to output a few numbers, specify “. ##”.

. ###” for two digits, “. ####” for 3 digits, and so on.

import java.text.DecimalFormat;

public class DecimalFormatSample2 {
  public static void main(String[] args) {
    final DecimalFormat decFormat = new DecimalFormat("###,###.####");
    final String str = decFormat.format(123.123456789);
    System.out.println(str); // 123.1235
  }
}

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL