Java number formatting - how to format Java numbers

Java number formatting FAQ: How do I format numbers for output on reports in Java programs?

Generally speaking you want to use the Java NumberFormat class and its descendants, such as the Java DecimalFormat class.

Quoting the API documentation, the Java DecimalFormat class "also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized."

Java number formatting example with Java NumberFormat

How about a concrete example? For instance, suppose I want to show a number like 100.00 on a report instead of the default printout value, which for a float is something like 100.0 or 100?

Here is an example using a class named NumberFormatTests. Note that I have shown the formatted and unformatted output values as the loop counter increases.

  import java.text.*;
  
  public class NumberFormatTests
  {
    public static void main (String[] args)
    {
      double amount = 100.0;
      NumberFormat nf = new DecimalFormat("#,###.00");
      for ( double d=0; d<200; d+=50.5 )
      {
        amount = amount + d;
        System.out.println( "" );
        System.out.println( "amount without formatting: " + amount );
        System.out.println( "amount with    formatting: " + nf.format(amount) );
      }
    }
  }

The output from this NumberFormat example program looks like this:

  amount without formatting: 100.0
  amount with    formatting: 100.00

  amount without formatting: 150.5
  amount with    formatting: 150.50

  amount without formatting: 251.5
  amount with    formatting: 251.50

  amount without formatting: 403.0
  amount with    formatting: 403.00

Java number formatting - Summary

I hope this simple Java number format example has been helpful. As you can see, you can use the Java NumberFormat and DecimalFormat classes like this to achieve whatever output format you want.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.