Wie wird der Double/Float-Wert in Java auf 2 Dezimalstellen gerundet?

Java - So runden Sie den Double / Float-Wert auf 2 Dezimalstellen

In Java gibt es einige Möglichkeiten,float oderdouble auf 2 Dezimalstellen zu runden.

Note
Lesen Sie dieseRoundingMode

1. DecimalFormat

DecimalExample.java

package com.example;

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

public class DecimalExample {

    private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {

        double input = 1205.6358;

        System.out.println("salary : " + input);

        // DecimalFormat, default is RoundingMode.HALF_EVEN
        System.out.println("salary : " + df.format(input));      //1205.64

        df.setRoundingMode(RoundingMode.DOWN);
        System.out.println("salary : " + df.format(input));      //1205.63

        df.setRoundingMode(RoundingMode.UP);
        System.out.println("salary : " + df.format(input));      //1205.64

    }

}

Ausgabe

salary : 1205.6358
salary : 1205.64
salary : 1205.63
salary : 1205.64

2. BigDecimal

BigDecimalExample.java

package com.example;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalExample {

    public static void main(String[] args) {

        double input = 3.14159265359;
        System.out.println("double : " + input);

        BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
        double salary = bd.doubleValue();

        System.out.println("salary : " + salary);

    }

}

Ausgabe

salary : 1205.6358
salary : 1205.64

3. Math.round

MathExample.java

package com.example;

public class MathExample {

    public static void main(String[] args) {

        double input = 1205.6358;

        System.out.println("salary : " + input);

        double salary = Math.round(input * 100.0) / 100.0;

        System.out.println("salary : " + salary);

    }

}

Ausgabe

salary : 1205.6358
salary : 1205.64

Erklärung, nur für Akademiezwecke, für 3 Dezimalstellen,*1000

input = 1205.6358;

Math.round(input * 100.0) / 100.0;

Math.round(120563.58) / 100.0;

120564 / 100.0;

salary = 1205.64