I using:
String str="300.0";
System.out.println(Integer.parseInt(str));
return an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300.0"
How can I parse this String to int?
thanks for help :)
Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer. parseInt takes that string value and returns a real number.
The method generally used to convert String to Integer in Java is parseInt() of String class.
The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float).
Here's how you do it:
String str = "300.0";
System.out.println((int) Double.parseDouble(str));
The reason you got a NumberFormatException
is simply that the string ("300.00", which is a floating point number) could not be parsed as an integer.
It may be worth mentioning, that this solution prints 300
even for input "300.99"
. To get a proper rounding, you could do
System.out.println(Math.round(Double.parseDouble("300.99"))); // prints 301
I am amazed no one has mentioned BigDecimal.
It's really the best way to convert string of decimal's to int.
Josuha Bloch suggest using this method in one of his puzzlers.
Here is the example run on Ideone.com
class Test {
public static void main(String args[]) {
try {
java.math.BigDecimal v1 = new java.math.BigDecimal("30.0");
java.math.BigDecimal v2 = new java.math.BigDecimal("30.00");
System.out.println("V1: " + v1.intValue() + " V2: " + v2.intValue());
} catch(NumberFormatException npe) {
System.err.println("Wrong format on number");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With