Formatting 0 to include decimal places using DecimalFormat

765 Views Asked by At
import java.math.BigDecimal; 
import java.text.DecimalFormat;

public class HelloWorld{

     public static void main(String []args){
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println("two  decimals: " + new BigDecimal(df.format(123.435435))) ;
        System.out.println("zero two decimal places: " + new BigDecimal(df.format(0.0000))) ;
        System.out.println("zero without a decimal place: " + new BigDecimal(df.format(0))) ;
     }
}

The output is:

three decimals: 123.44
zero two decimal places: 0
zero without a decimal place: 0

Now, DecimalFormat df = new DecimalFormat("#.##");

This is something that is used widely in my application and I do not, yet, have an option to modify this. How can I print 0 as 0.00 in the above program?

2

There are 2 best solutions below

4
Monopole Magnet On

According to the Javadoc formatting with '#' will show zero as absent. You can use '0' instead to show a decimal place unconditionally, even if the digit concerned is zero.

Note that BigDecimals are used for calculations where high precision is required, e.g. financial applications. If you just need to print formatted numbers, you don't really need them.

  DecimalFormat df = new DecimalFormat("#.##");
  DecimalFormat dfWithZeroes = new DecimalFormat("0.00");
  System.out.println("two  decimals: " + df.format(123.435435));
  System.out.println("zero two decimals: " + dfWithZeroes.format(0.0000));
  System.out.println("zero without a decimal: " + df.format(0));

With BigDecimals:

  System.out.println("two  decimals: " + new BigDecimal(df.format(123.435435)));
  System.out.println("zero two decimals: " + new BigDecimal(dfWithZeroes.format(0.0000)));
  System.out.println("zero without a decimal: " + new BigDecimal(df.format(0)));
0
Sara On
import java.math.BigDecimal; 
import java.text.DecimalFormat;

public class HelloWorld{

public static void main(String []args){
  DecimalFormat df = new DecimalFormat("#.##");

  System.out.println("");
  System.out.println("------------Handling zero with Decimal Formatter API------------");
  System.out.println("");


  DecimalFormat dfWithZeroes = new DecimalFormat("0.0");
  System.out.println("two  decimals: " + df.format(123.435435));
  System.out.println("zero two decimals: " + dfWithZeroes.format(0));
  System.out.println("zero without a decimal: " + df.format(0));

  System.out.println("");
  System.out.println("------------Handling zero with BigDecimal API------------");
  System.out.println("");

  BigDecimal zero = BigDecimal.ZERO;
  System.out.println("Zero without scaling " + zero);
  System.out.println("Zero with scale 1: " + zero.setScale(1));
  System.out.println("Zero with scale 2: " + zero.setScale(2));
  System.out.println("Zero with scale 3: " + zero.setScale(3));
 }
}