gpt4 book ai didi

java - 将字符串转换为整数或 int 的最佳方法

转载 作者:行者123 更新时间:2023-12-01 22:10:52 25 4
gpt4 key购买 nike

这可能之前问了太多次,但是......

String str = "74.0";

假设我有“74.05”,而我只需要74。以下是我的一些方法..

Integer.parseInt(str); //would result to java.lang.NumberFormatException
(int) Double.parseDouble(str); //working
new BigDecimal(str).intValue(); //I like this

我想将此字符串(str)转换为intInteger,最好的方法是什么?

最佳答案

java.lang.NumberFormatException 是由于您尝试将 double 文字转换为 int 类型所致。

没有最好的方法,而是使用

Double.parseDouble("74.05");

而不是

Double.valueOf("74.05");

取决于您对 double 基元类型或 Double 对象类型的需要。

如果您需要整数类型,可以像这样舍入 double 值:

Math.round(Double.parseDouble("74.05"));

或者简单地转换double以仅获取整数部分

(int)Double.parseDouble("74.05")

new BigDecimal(str).intValue(); 无疑是最差的选择,因为可能会导致 Oracle 中所述的意外结果> 文档(见粗体):

public int intValue()

Converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short as defined in section 5.1.3 of The Java™ Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

<小时/>

与问题无关,当您需要从 int 值实例化 Integer 时,有时有一种更快的方法。来自 java.lang.Integer class 文档:

public static Integer valueOf(int i)

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

关于java - 将字符串转换为整数或 int 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31879832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com