The Java code is as follows:
String s = "0.01"; int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the , . parseFloat will parse a decimal number, but only understands . as the decimal point, not , , even in locales where , is the decimal point.
Numbers are so important in Java that six of the eight primitive data types are numeric types. There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
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.
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