Format number to 2 decimal places in Java

0
33

Quick example to format any type of number – int, long, float, and double to 2 decimal places in Java

DecimalFormat(“0.00”)

import java.text.DecimalFormat;

public class FormatAnyNumber 
    private static final DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) 
        int num1 = 12345;
        long num2 = 12345;
        float num3 = 12345.6f;
        double num4 = 12345.6789;

        System.out.println("int:    " + df.format(num1));
        System.out.println("long:   " + df.format(num2));
        System.out.println("float:  " + df.format(num3));
        System.out.println("double: " + df.format(num4));
    

Output

int: 12345.00 long: 12345.00 float: 12345.60 double: 12345.68

Points to note…

  1. int and long number has no decimal places, appended “00” at the end for 2 decimal places
  2. float number has only one decimal place, appended “0” at the end for 2 decimal places
  3. double number has 4 decimal places, rounded to 2 decimal places.

RoundingMode

By default, DecimalFormat use RoundingMode.HALF_EVEN for rounding. You can use other rounding modes as follows:-

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


public class FormatAnyNumber 
    private static final DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) 
        double num = 12345.6789;

        df.setRoundingMode(RoundingMode.UP);
        System.out.println("double rounding up  : " + df.format(num));
        df.setRoundingMode(RoundingMode.DOWN);
        System.out.println("double rounding down: " + df.format(num));
    

Output

double rounding up : 12345.68 double rounding down: 12345.67

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here