How do you preserve integers in DecimalFormat in Java?

To retain integers in Java using DecimalFormat, you can utilize the following code:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double number = 123.456789;
        
        DecimalFormat df = new DecimalFormat("#");
        String result = df.format(number);
        
        System.out.println(result);
    }
}

The output result is:

123

In this example, we utilized the DecimalFormat class to format a double type number. By using the # format pattern, we specified to only keep the integer part. The formatted result is saved in a string variable and then printed out.

You can also modify the formatting mode as needed. For example, if you want to keep two decimal places and round to the nearest integer, you can use the following code.

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double number = 123.456789;
        
        DecimalFormat df = new DecimalFormat("#.00");
        String result = df.format(number);
        
        System.out.println(result);
    }
}

The output result is:

123.46

In this example, we used the format #.00 to round numbers to the nearest whole number while keeping two decimal places.

bannerAds