BigDecimal:https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
DecimalFormat:https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
Math:https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
apache commons-math:https://commons.apache.org/proper/commons-math/
maven repository:https://mvnrepository.com/
算法 | 说明 |
---|---|
ROUND_UP | 舍入模式从零舍入 |
ROUND_DOWN | 舍入模式向零舍入 |
ROUND_CEILING | 舍入模式向正无穷大舍入 |
ROUND_FLOOR | 舍入模式向负无穷大舍入 |
HALF_UP | 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下向上舍入 |
HALF_DOWN | 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下向下舍入 |
HAIL_EVEN | 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下,向偶数邻居舍入 |
UNNECESSARY | 舍入模式断言所请求的操作具有精确的结果,因此不需要舍入 |
double num = 3333.445555; // BigDecimal BigDecimal bigDecimal = new BigDecimal(num); bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP); System.out.println("bigDecimal="+ bigDecimal.doubleValue());
double num = 3333.445555; // DecimalFormat DecimalFormat decimalFormat = new DecimalFormat("#.##"); String numByDF = decimalFormat.format(num); System.out.println("decimalFormat="+ numByDF);
double num = 3333.445555; // Math double numByM = Math.round(num*100.0) / 100.0; System.out.println("numByM="+ numByM);
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math3</artifactId> <version>3.6.1</version> </dependency>
double num = 3333.445555; // commons-math3 double numByM3 = Precision.round(num, 2); System.out.println("numByM3="+ numByM3);
double num = 3333.445555; // String#format String numByStr = String.format("%.2f", num); System.out.println("String.format="+ numByStr);