Reputation: 37
I'm trying to convert a string "3.0" to int in java. I tried to convert using Integer.parseInt, but it throws an exception. Any idea how can I convert the string with decimal values to int in java and kotlin
String value = "3.0";
int i = Integer.parseInt(value);
Upvotes: 2
Views: 5678
Reputation: 19544
You can't parse "3.0"
as an integer, because it represents a floating-point value. Your best bet is to parse it as such using the handy build-in functions (Double.parseDouble("3.0")
or Float.parseFloat("3.0")
) and then convert that to an integer.
How you convert it depends on how you want to treat the decimal portion
discard it (number moves closer to zero): cast to int
(int) 2.5
= 2
, (int) -2.5
= -2
round it to the nearest integer: Math.round()
, then cast*
(int) Math.round(2.5)
= 3
, (int) Math.round(-2.5)
= -3
round to the higher integer (number moves towards positive infinity): Math.ceil()
then cast
(int) Math.ceil(2.5)
= 3
, (int) Math.ceil(-2.5)
= 2
round to the lower integer (number moves towards negative infinity):
Math.floor()
then cast
(int) Math.floor(2.5)
= 2
, (int) Math.floor(-2.5)
= -3
*Math.round
takes either a float
or a double
, and produces an int
or a long
respectively, so you don't need cast to int
if you use a float
. All the other Math
methods take double
s though, so I'm using that for consistency
Kotlin is the same, the equivalents are:
"2.5".toDouble()
2.5.toInt()
2.5.roundToInt()
ceil(2.5).toInt()
floor(2.5).toInt()
(functions are in kotlin.math
)
Upvotes: 1
Reputation: 8335
In kotlin you can do this as
val str = "3.0"
val result = str.toDouble().toInt()
Upvotes: 4
Reputation: 425033
Convert the string to an integer, then parse:
int i = Integer.parseInt(str.replaceAll("\\..*", ""));
This removes the dot and everything after it, which is effectively what casting a floating point type to integer does.
Upvotes: 2
Reputation: 459
String value = "3.0";
int i = (int) Float.parseFloat(value);
Upvotes: 1