如何对十进制数执行 Integer.parseInt() ?

Java 代码如下:

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

但是这会抛出 NumberFormatException... 会出什么问题呢?

250225 次浏览

0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.

String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.

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

Use,

String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();

use this one

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

This kind of conversion is actually suprisingly unintuitive in Java

Take for example a following string : "100.00"

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

int i = atoi(decimalstring);

Java : mandatory passage by Double (or Float) parse, followed by a cast

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

Java sure has some oddities up it's sleeve

Using BigDecimal to get rounding:

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();

suppose we take a integer in string.

String s="100"; int i=Integer.parseInt(s); or int i=Integer.valueOf(s);

but in your question the number you are trying to do the change is the whole number

String s="10.00";

double d=Double.parseDouble(s);

int i=(int)d;

This way you get the answer of the value which you are trying to get it.

One more solution is possible.

int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))

Example:

Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))

Output

10