David Wallace
David Wallace

Reputation: 37

How can I convert a decimal string value to int in java

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

Answers (4)

cactustictacs
cactustictacs

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 doubles though, so I'm using that for consistency


Kotlin is the same, the equivalents are:

  • parse: "2.5".toDouble()
  • discard decimal: 2.5.toInt()
  • round to nearest: 2.5.roundToInt()
  • round to higher: ceil(2.5).toInt()
  • round to lower: floor(2.5).toInt()

(functions are in kotlin.math)

Upvotes: 1

mightyWOZ
mightyWOZ

Reputation: 8335

In kotlin you can do this as

val str = "3.0"
val result = str.toDouble().toInt()

Upvotes: 4

Bohemian
Bohemian

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

Syed Muhammad Humayun
Syed Muhammad Humayun

Reputation: 459

String value = "3.0";
int i = (int) Float.parseFloat(value);

Upvotes: 1

Related Questions