SoFunction
Updated on 2025-04-11

Java double retains two decimal places

Java double retains two decimal places

In Java, you can useDecimalFormatorTo preserve two decimal places of the double type.

Here are two examples:

Using DecimalFormat

import ;

public class Main {
    public static void main(String[] args) {
        double number = 123.4567;
        DecimalFormat df = new DecimalFormat("#.00");
        String result = (number);
        (result);  // Output: 123.46    }
}

use

public class Main {
    public static void main(String[] args) {
        double number = 123.4567;
        String result = ("%.2f", number);
        (result);  // Output: 123.46    }
}

Both examples round numbers of double type to two decimal places.

Notice :

  • DecimalFormatRounding by default
  • andThe "%.2f" format also means rounding to two decimal places

Java double type retains three decimal places

 /**Tool class, call it directly, and you don't need to change anything
      * Provides accurate decimal rounding.
      * @param v Counts that need to be rounded
      * @param scale How many digits are retained after the decimal point
      * @return The result after rounding
      */
    public static double round(double v,int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal((v));
        BigDecimal one = new BigDecimal("1");
        return (one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
/*
 Main test
 */
 public static void main(String[] args) {
        double d1 = 0.234566d;
        double d2 = 0.234566d;
        ("===== " + round(d1,3));
        ("-----" + round(d2,1));
}

/*
 Results Display
 */
===== 0.235
----- 0.2

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.