Java - Comment arrondir la valeur double / flottante à 2 décimales
En Java, il existe plusieurs façons d'arrondirfloat
oudouble
à 2 décimales.
Note
Lire ceciRoundingMode
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 } }
Sortie
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); } }
Sortie
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); } }
Sortie
salary : 1205.6358 salary : 1205.64
Explication, juste à des fins académiques, pour 3 décimales,*1000
input = 1205.6358; Math.round(input * 100.0) / 100.0; Math.round(120563.58) / 100.0; 120564 / 100.0; salary = 1205.64