在 Java 中,对 Double(双精度浮点数)进行“取整”有多种方式,具体取决于你想要的取整规则。下面按常见场景说明:
Math.round(返回 long 或 int)Double d = 3.6;
long l = Math.round(d); // 4
int i = (int) Math.round(d); // 4
⚠️ 注意:返回的是 long,精度安全。
Double d = 3.9;
int i = d.intValue(); // 3
// 或
int i2 = (int)(double)d; // 3
⚠️ 负数也会向零:(-3.9 → -3)
Math.floorDouble d = 3.2;
double r = Math.floor(d); // 3.0
Double d2 = -3.2;
double r2 = Math.floor(d2); // -4.0
Math.ceilDouble d = 3.1;
double r = Math.ceil(d); // 4.0
BigDecimal(推荐,精度高)Double d = 3.14159;
double r = BigDecimal.valueOf(d)
.setScale(2, RoundingMode.HALF_UP)
.doubleValue(); // 3.14
Double 而非 int/long如果你不想改变类型,只是取整值:
Double d = 3.7;
Double result = Math.floor(d); // 3.0
| 需求 | 方法 |
|---|---|
| 四舍五入 | Math.round |
| 向零取整 | (int) d |
| 向下取整 | Math.floor |
| 向上取整 | Math.ceil |
| 高精度 | BigDecimal |
如果你有具体业务场景(如金额、分页、算法),我可以给你更合适的建议。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。