Skip to content

Instantly share code, notes, and snippets.

@sasaki-shigeo
Created September 15, 2012 13:18
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sasaki-shigeo/3727810 to your computer and use it in GitHub Desktop.
Save sasaki-shigeo/3727810 to your computer and use it in GitHub Desktop.
Conversion from/to Numeric Type in Scala (Scala における数値型の変換)
import math._
1L // Long型の 1
1:Long // Long型の 1
127:Byte // Byte型の 127
32767:Short // Short型の 32767
(1+2).toLong // Long型への変換
(2+3) toLong // Long型への変換
1 + 2 toByte // (1 + 2).toByte と同じ
          // 後置関数の優先順位が低いので 1 + (2 toByte) とは解釈されない
16 toShort // Short 型への変換
32 toFloat // Float 型への変換
64 toDouble // Double 型への変換
2.5 toInt // Int への変換(切り捨て)
-2.5 toInt // -2 (0 に近づく方向に切り捨てられる)
// scala.math パッケージの関数
// 動作は java.lang.Math クラスの関数と同じ
floor(3.5) // 3.0 切り下げ
floor(-3.5) // -4.0 切り下げは負の(無限大の)方向に進む
ceil(3.5) // 4.0 切り上げ
ceil(-3.5) // -3.0 切り上げは正の(無限大の)方向に進む
round(3.5) // 4L 偶数丸め(四捨五入に似ているが異なる)
round(4.5) // 4L ちょうど真ん中の場合は,結果が偶数になる方を選ぶ
// 四捨五入関数を自分で定義する
def 四捨五入(x: Double): Int = math.floor(x + 0.5).toInt
// 文字列への / からの変換
123.toString // 文字列への変換
123 toString // 例によってドットは省略できる
3.14 toString // Double から String へ
"123" toInt // 文字列から数値へ
"3.14" toDouble // 文字列から数値へ
// 十六進法文字列,八進法文字列へ
255.toHexString // "ff"
255.toOctalString // "377"
// 十六進表記,八進表記の文字列を整数に変換するときは Java の機能を用いる
Integer.parseInt("77", 8) // 63 八進表記の "77" を十進数に直すと 63
java.lang.Long.parseLong("123456789ABCDEF", 16) // 十六進数
// Java の Long を呼ぶためには java.lang.Long と指定する
// オーバーフローに注意
128:Byte // エラー(Byte.MaxValue == 127 なので)
128 toByte // -128 (二進数で 1000 0000 は -128 なので)
32767: Short // OK
32768: Short // エラー
32768 toShort // -32768
val tooBig = Double.MaxValue
math.sqrt(tooBig * tooBig) // 計算途中で無限大になったら,平方根をとっても無限大
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment