How to format numbers in Java? - NumberFormat Example

You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them. Most numbers that are used to represent monetary value e.g. price, amount, etc require a comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollars then you would like to see it as 1,000,000 rather than 1000000. Clearly, the first one is more readable than the second one. Of course, you can further format to add currency based upon locale, but this tutorial is not about that. 

In this tutorial, we are just looking to format numbers and group them. It's the second part of my number formatting article, in the first part you have learned how to format floating-point numbers in Java, and in this article shows step-by-step examples to group numbers and add commas between them.

There are mainly two ways to group numbers in Java, first by using NumberFormat class and second by using DecimalFormat class. Actually, DecimalFormat is subclass of NumbeFormat, and method used to enable grouping e.g. setGroupingUsed() is defined there, but you cannot specify grouping size there.

Grouping size is the number of digits between grouping separators in the integer portion of a number and by default, NumberFormat uses a group size of three. So if grouping is your need and you are happy with a grouping size of three then go for NumberFormat but if you want advanced formatting and custom grouping size then go for DecimalFormat class.

If you are a beginner in Java and interested in learning essential features e.g. text formatting, I suggest taking a look at Java: A Beginner's Guide by Herbert Schildt, a must-read book for Java beginners.




Java Program to add comma into Numbers

Here is our complete Java example to format numbers and add commas into them. All code is inside the main method to make it easy to run and understand. In order to add commas to a number, we first need to create an instance of NumberFormat class. 

Since NumberFormat is a singleton in Java, instead of creating we get the instance by calling the NumberFormat.getInstance() method.

Now to enable grouping, we call the setGroupingUsed() method and pass true, this will enable grouping, all done now. In order to print numbers with a comma, just call the format() method of NumberFormat class and it will print it accordingly.

By default, NumberFormat uses a grouping size of three, so you will see a comma (grouping separator) after every three digits on the integer portion of the number starting from the right. If you want to use a custom grouping size, you need to use DecimalFormat class. It provides a method called setGroupingSize(int size) which can customize grouping size.

How to add comma into number by formatting


Here is our Java program to add commas into numbers by using NumberFormat and DecimalFormat class :

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * Java Program to show how to add comma to numbers in Java e.g. integers.
 * Normally numbers which is used to represent monetary value e.g. 
 * price, amount etc require
 * commas to be added to improve readability and follow conventions.
 * This article shows step by
 * step example to add commas on numbers.
 *
 * @author Javin Paul
 */
public class NumberFormatExample{

    public static void main(String args[]) {

        // Example 1 - by using NumberFormat class
        NumberFormat myFormat = NumberFormat.getInstance();
        myFormat.setGroupingUsed(true); // this will also round numbers, 3
        // decimal places

        double[] numbers = {1.16763, 443330, 3, 517827.17};

        System.out.println("adding commas to number in Java 
                 using NumberFormat class");
        for (double d : numbers) {
            System.out.println(myFormat.format(d));
        }

        // Example 2 - By using DecimalFormat class
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        decimalFormat.setGroupingUsed(true);
        decimalFormat.setGroupingSize(3);

        System.out.println("adding commas to number in Java 
                  using DecimalFormat class");
        for (double d : numbers) {
            System.out.println(decimalFormat.format(d));
        }
    }

}



Output
adding commas to number in Java using NumberFormat class
1.168
443,330
3
517,827.17
adding commas to number in Java using DecimalFormat class
1.17
443,330
3
517,827.17


Important Points to remember about adding commas to Number

Here are a couple of important things you should remember about adding commas to a number in Java

1) You can use NumberFormat class or DecimalFormat class to enable grouping and introduce comma between digits.

2) You can enable grouping by calling NumberFormat.setGroupingUsed(true) method, passing true argument enable the grouping.

3) Default grouping size is three, which means a comma will be inserted after 3 digits from the right and only on the integer portion of a number.

4) You can increase grouping size by calling a setGroupingSize(size) method of DecimalFormat class e.g. setGroupingSize(4) will add a comma after every four digits starting from a decimal point towards left.



That's all about how to add commas to a number in Java. It's just a small part of a bigger feature of formatting numbers in Java.  Formatting numbers in Java is a critical aspect of creating applications that present data in a clear and user-friendly manner. 

The NumberFormat class provides a versatile and locale-sensitive approach to achieve consistent number formatting across different regions and languages. Whether you're working with simple numeric outputs or complex financial data, understanding and utilizing NumberFormat in Java empowers developers to enhance the readability and usability of their applications. 

By incorporating these formatting techniques, developers can create applications that cater to diverse audiences while maintaining precision and clarity in numerical representations. I also suggest taking a look at a couple of beginner's Java guide to understanding more about these useful features. 

If you like you can follow either Head First Java 2nd Edition by Kathy Sierra or  Core Java Volume 1 and 2 by Cay S. Horstmann. Both are good books and have chapters to explain text and number formatting in Java.



4 comments:

  1. I want to group by 3 without comma

    ReplyDelete
  2. Its very simple with my code you can add any thing

    code is


    package com.program;

    public class Main {
    public static void main(String[] args) {
    // String tha we need to compare or int or any thing can work
    String input = "Madebyanand123456789011111111111111111122222222222223333333";


    String lop = "";

    //int l = 0 // For International system

    int l = 1;// It is just for adding comma in our text

    for (int i = 1; i < input.length() + 1; i++) {//This loop just add all char value
    // from the string
    lop = lop + input.charAt(input.length() - i);//it is for reversing the value
    //because we cant add comma from end side
    l++;
    if (l % 3 == 0) {
    lop = lop + ",";//use any thing. I have added comma here
    }

    }
    for (int i = 1; i < lop.length() + 1; i++) {
    System.out.print(lop.charAt(lop.length() - i));//Now again reversing
    // the string and printing it
    }
    }
    }

    //Advantage of this code is that you can use it to format it very large numbers or string
    //Using number format you cant format very large number

    ReplyDelete
  3. when i used your code to print out large numbers as a String, i would sometimes get a comma as my first Char

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.