La classe Math
Math.round(1.082 * 1500); // arrondi Math.max(1500, 2000); // 2000 Math.ceil(4.1); // 5.0 Math.random(); // [0,1[ Math.sqrt(16); // 4.0
BigDecimal pour l'argent
Jamais double pour l'argent —
0.1 + 0.2 ne vaut pas exactement 0.3 en flottant. Pour des montants, on utilise BigDecimal.import java.math.BigDecimal; import java.math.RoundingMode; BigDecimal prix = new BigDecimal("1.082"); // via String ! BigDecimal litres = new BigDecimal(1500); BigDecimal cout = prix.multiply(litres) .setScale(2, RoundingMode.HALF_UP); // 1623.00
Construire depuis une String —
new BigDecimal("1.082") et non new BigDecimal(1.082), sinon on réintroduit l'imprécision du double.🛢️ Sur le projet Fioul Groupé
Le coût d'une commande de fioul (prixLitre × litres) se calcule en BigDecimal pour éviter tout centime perdu — c'est le pendant Java du type DECIMAL(6,3) choisi côté MySQL. Cohérence de bout en bout : DECIMAL en base, BigDecimal en Java.
À retenir
- Math : arrondis, min/max, racine, aléatoire.
- Pour l'argent : BigDecimal, jamais double/float.
- Construire BigDecimal depuis une String ; setScale + RoundingMode.
- DECIMAL (SQL) ↔ BigDecimal (Java) : cohérence des montants.