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.