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

标签 java

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

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/

相关文章:

java - 无法获取 JOptionPane 字符串输入来匹配字符串值

java - 如何在Android中读取文件

java - GWT 中水平面板中无法解释的间距

java - 连接阶段后 "java.io.IOException: Connection timed out"的含义

java - 获取带有附件的 Notes Document 的内容到 Solr Document

java - 如何解决tomcat上的以下异常

java - Log4j2 自定义 Hibernate Appender 的内存泄漏

java - 识别文件中的音频样本

java - Web 应用程序服务器过载

java - Java-多线程