1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Scala】文字列(String)を数値(Int, Doubleなど)に変換する

Last updated at Posted at 2020-06-14

1. 基本の変換

Scalaで文字列(String)を数値(Int, Doubleなど)に変換するにはtoInttoDoubleといったメソッドを使います。

文字列を数値型に変換
scala> "10".toInt
val res0: Int = 10

scala> "3.14".toDouble
val res1: Double = 3.14

基本的に、数値として解釈できれば変換可能です。
また、IntDouble以外の数値型に変換するためのメソッドも用意されています。

その他のパターン・型
scala> "-100".toInt  // 負数も変換可能
val res2: Int = -100

scala> "3".toDouble  // 小数型に変換する場合は小数点がなくても可
val res3: Double = 3.0

scala> "12345678900".toLong  // Long
val res4: Long = 12345678900

scala> "1.234".toFloat       // Float
val res5: Float = 1.234

scala> "12345".toShort       // Short
val res6: Short = 12345

scala> "123".toByte          // Byte
val res7: Byte = 123

数値ではありませんが、真偽値の文字列をBoolean型に変換することも可能です。

真偽値型に変換
scala> "true".toBoolean
val res8: Boolean = true

scala> "false".toBoolean
val res9: Boolean = false

2. より安全な変換

上記のメソッド群は、数値として解釈できない文字列の場合にjava.lang.NumberFormatExceptionを投げます。1

数値として解釈できない文字列の場合
scala> "hello".toInt
java.lang.NumberFormatException: For input string: "hello"
  at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.base/java.lang.Integer.parseInt(Integer.java:652)
  at java.base/java.lang.Integer.parseInt(Integer.java:770)
  at scala.collection.StringOps$.toInt$extension(StringOps.scala:889)
  ... 32 elided

scala> "3.14".toInt // 小数をIntに変換しようとしてもエラー
java.lang.NumberFormatException: For input string: "3.14"
()

数値として解釈できない文字列を変換する場合、toIntOptiontoDoubleOptionを使うことで、安全に変換することができます。2
これらのメソッドは与えられた文字列が数値に変換できれば変換結果をSomeに包み、変換できなければNoneを返します。

Optionを利用した安全な変換
scala> "100".toIntOption    // 変換に成功したら数値をSomeに包む
val res10: Option[Int] = Some(100)

scala> "hello".toIntOption  // 失敗はNone
val res11: Option[Int] = None

scala> "123.45".toDoubleOption     // Double(成功)
val res12: Option[Double] = Some(123.45)

scala> "foo123.45".toDoubleOption  // Double(失敗)
val res13: Option[Double] = None

scala> "".toIntOption // 空文字列もNone
val res14: Option[Int] = None

こちらもIntDoubleに限らず、一通りの数値型(とBoolean型)で用意されています。

その他の数値型(Noneになるパターンは省略)
scala> "12345678900".toLongOption  // Long
val res15: Option[Long] = Some(12345678900)

scala> "1.234".toFloatOption       // Float
val res16: Option[Float] = Some(1.234)

scala> "12345".toShortOption       // Short
val res17: Option[Short] = Some(12345)

scala> "123".toByteOption          // Byte
val res18: Option[Byte] = Some(123)

scala> "false".toBooleanOption     // Boolean
val res19: Option[Boolean] = Some(false)

確実に目当ての型に変換できるとわかりきっているケースでない限りは、こちらを使った方が安全ですし、例外を補足する手間も減りますね。

おまけ: Scala 2.12以前の場合

上記のtoXXXOption系のメソッドは、Scala 2.13以上のバージョンでなければ使用できません。
Scala 2.12以前で同等の処理をしたい場合は、下記の@suinさんの記事などを参考にしていただければと思います。
Scala: Stringを安全にIntに変換する


最後までお読み頂きありがとうございました。 質問や不備についてはコメント欄か[Twitter](https://twitter.com/ka2_kamaboko)までお願いします。
  1. toBooleanの場合はjava.lang.IllegalArgumentExceptionを投げます。

  2. (Stringの)toXXXOption系のメソッドはScala 2.13.0で追加されました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?