Ich versuche, einen doppelten Wert für Steuerberechnungen in Java zu runden. Ich erwarte, dass der Wert 7,90518 auf 7,91 gerundet wird, aber das Ergebnis, das ich bekomme, ist 7,90 nach der Formatierung. Hier ist der relevante Teil meines Codes: < /p>
public class Main {
public static void main(String[] args) {
double var1 = 7.90518;
double roundedValue = new BigDecimal(var1)
.divide(BigDecimal.valueOf(0.05), 10, RoundingMode.HALF_UP)
.setScale(0, RoundingMode.HALF_UP)
.multiply(BigDecimal.valueOf(0.05))
.doubleValue();
System.out.println("formatted but not rounded result: " + formatPriceForTax(var1));
System.out.println("unformatted, but rounded value result: " + roundedValue);
System.out.println("formatted and rounded result: " + formatPriceForTax(roundedValue));
}
private static String formatPriceForTax(final Double d) {
BigDecimal bd = BigDecimal.valueOf(d).setScale(2, RoundingMode.DOWN);
return new DecimalFormat("###,##0.00").format(bd);
}
}
< /code>
Erwartete Ausgabe: < /p>
formatiert, aber nicht abgerundetes Ergebnis: 7,91
unformatiert, aber abgerundetes Wertergebnis: 7,91
Formatiert und abgerundetes Ergebnis: 7,91 < /p>
-Forporte. Ergebnis des abgerundeten Wertes: 7,9
formatiertes und abgerundetes Ergebnis: 7,90 < /p>
Es sieht so aus, als würde ich irgendwo Präzision verlieren oder falsch formatieren. Warum kehrt FormatPriceFortax 7.90 anstelle von 7.91 zurück, selbst wenn die Eingabe mathematisch näher an 7.91 ist?>
Unerwartetes Rundungsverhalten bei der Verwendung von Bigdecimal und Decimalformat in Java ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post