How to make Integer.parseInt () for a decimal number?

Java code is as follows:

String s = "0.01"; int i = Integer.parseInt(s); 

However, this throws a NumberFormatException ... What could be wrong?

+48
java integer parsing
Sep 20 '09 at 13:13
source share
8 answers

0.01 is not an integer (integer), so of course you cannot parse it. Use Double.parseDouble or Float.parseFloat .

+47
Sep 20 '09 at 13:16
source share
— -
 String s = "0.01"; double d = Double.parseDouble(s); int i = (int) d; 

The reason for the exception is that the integer does not contain rational numbers (= mostly fractions). So, trying to parse 0.3 into int is nonsense. A double or float data type may contain rational numbers.

The way Java passes double to int is done by removing the part after the decimal separator by rounding to zero.

 int i = (int) 0.9999; 

i will be zero.

+63
Sep 20 '09 at 13:17
source share

Using

 String s="0.01"; int i= new Double(s).intValue(); 
+18
Sep 20 '09 at 13:56
source share
 String s="0.01"; int i = Double.valueOf(s).intValue(); 
+11
Apr 03 '13 at 14:08
source share

This kind of conversion is actually incredibly unintuitive in Java

Take, for example, the following line: "100.00"

C: a simple standard library function since at least 1971 ( Where did the name `atoi` come from? )

 int i = atoi(decimalstring); 

Java: mandatory pass through double (or Float) parsing followed by listing

 int i = (int)Double.parseDouble(decimalstring); 

Java probably has some oddities up its sleeve

+6
Sep 09 '13 at 13:11
source share

Use Double.parseDouble(String a) what you are looking for is not an integer since it is not an integer.

+2
Sep 20 '09 at 13:53
source share

use this

int number = (int) Double.parseDouble(s);

+2
Apr 05 '13 at 2:07 on
source share

Using BigDecimal to round:

 String s1="0.01"; int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact(); String s2="0.5"; int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact(); 
+2
Mar 18 '16 at 9:46
source share



All Articles