How to Format a Number in Java


This examples shows how to format a number.
This is often useful if you have either a very large number which will not be formatted well just using the normal System.out. or if you have a number that contains many decimals that you want to reduce to just a few.
In this example we format a large number to be readable. In order to do so we use the DecimalFormat class to which we pass the format we want to use (#0.00).
The format tells the DecimalFormat to present the number with two decimals. The actual formatting is done by calling the format() method on the DecimalFormat object.
Notice the difference when the accountBalance number is printed out before the formatting is done, and then afterwards.


package com.javadb.examples;

import java.text.DecimalFormat;

public class Main
{
    public static void main(String[] args)
    {
        double accountBalance = 10765880.2048;
        DecimalFormat formatter = new DecimalFormat("#0.00");

        System.out.println(accountBalance);

        System.out.println(formatter.format(accountBalance));
    }
}

The output from the code above is:

1.07658802048E7
10765880,20

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: