如何在 java 中将十进制字符串值转换为 int

How can I convert a decimal string value to int in java

我正在尝试将字符串“3.0”转换为 java 中的 int。我尝试使用 Integer.parseInt 进行转换,但它引发了异常。知道如何在 java 和 kotlin

中将具有十进制值的字符串转换为 int
String value = "3.0";
int i = Integer.parseInt(value);
String value = "3.0";
int i = (int) Float.parseFloat(value);

将字符串转换为整数,然后解析:

int i = Integer.parseInt(str.replaceAll("\..*", ""));

这会删除点及其后的所有内容,这实际上就是将浮点类型转换为整数所做的。

在科特林中你可以这样做

val str = "3.0"
val result = str.toDouble().toInt()

您不能将 "3.0" 解析为整数,因为它表示浮点值。最好的办法是使用方便的内置函数(Double.parseDouble("3.0")Float.parseFloat("3.0"))对其进行解析,然后将 that 转换为整数。

如何转换它取决于你想如何处理小数部分

  • 丢弃它(数字向零移动):转换为int

    (int) 2.5 = 2, (int) -2.5 = -2

  • 四舍五入到最接近的整数Math.round(),然后投*

    (int) Math.round(2.5) = 3, (int) Math.round(-2.5) = -3

  • 四舍五入到更高的整数(数字向正无穷大移动):Math.ceil()然后投

    (int) Math.ceil(2.5) = 3, (int) Math.ceil(-2.5) = 2

  • 舍入到较低的整数(数字向负无穷大移动): Math.floor() 然后投

    (int) Math.floor(2.5) = 2, (int) Math.floor(-2.5) = -3

*Math.round 采用 floatdouble,并分别生成 intlong,因此如果您使用 float,则不需要强制转换为 int。所有其他 Math 方法都需要 doubles,所以我使用它是为了保持一致性


Kotlin同理,等价物为:

  • 解析: "2.5".toDouble()
  • 舍弃小数2.5.toInt()
  • 四舍五入到最近的2.5.roundToInt()
  • 向上舍入ceil(2.5).toInt()
  • 向下取整floor(2.5).toInt()

(函数在kotlin.math