This might asked too many times before but...
String str = "74.0";
let say I have "74.05"
and I only need the 74
. Below are some of my ways..
Integer.parseInt(str); //would result to java.lang.NumberFormatException
(int) Double.parseDouble(str); //working
new BigDecimal(str).intValue(); //I like this
I want this string( str
) converted to int
or Integer
, what is the best way to do it?
The java.lang.NumberFormatException
is due to the fact that you are trying to convert a double
literal to a an int
type.
There is not a best way but the usage of
Double.parseDouble("74.05");
instead of
Double.valueOf("74.05");
depends on your need of a double
primitive type or a Double
object type.
If you need an integer type, you can round the double value like this:
Math.round(Double.parseDouble("74.05"));
or simply cast the double
to obtain the integral part only
(int)Double.parseDouble("74.05")
The new BigDecimal(str).intValue();
is surely the worst choiche because can lead to unespected results as stated in the Oracle documentation (see the bold):
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 .
Unrelated to the question, there is a sometime faster way when you need to instantiate an Integer
from an int
value. From the java.lang.Integer
class
documentation:
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.
int x = (int) Double.parseDouble(s);
ran in 3 nano seconds,
int y = new BigDecimal(s).intValue();
ran in 8 nano seconds
a really somewhat unorthodox solution would be:
Integer.parseInt(str.split("\\.")[0]);
but it works with Strings like "74.09" and Strings like "74" and so on
How about
Integer myNum = Integer.parseInt(str.substring(0, str.indexOf("."));
since the OP explicitly wanted NO rounding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.