如何通过向下舍入来将一个double转换为Java中的一个int? [英] How to cast a double to an int in Java by rounding it down?

查看:74
本文介绍了如何通过向下舍入来将一个double转换为Java中的一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中将double转换为int,但数值必须总是向下舍入。即99.99999999 - > 99

I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99

推荐答案

强制转换为int会隐式删除任何小数。无需调用Math.floor()(假设为正数)

Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)

只需使用(int)类型转换,例如:

Simply typecast with (int), e.g.:

System.out.println((int)(99.9999)); // Prints 99

这就是说,它与 Math.floor 向负无穷大(@Chris Wong)舍入

This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (@Chris Wong)

这篇关于如何通过向下舍入来将一个double转换为Java中的一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆