0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

数値型の種類

Posted at

Kotlinの数値型はByte、Short、Int、Long、Float、Doubleの6種類ある。

整数であれば、異なる型でも計算が可能。

val i: Byte = 30
val j: Int = 20
i + j
// 50

少数の場合も計算できるが減算や、型が異なると誤差が生じる。BigDecimal型を使用する。

val i: Double = 0.2
val j: Double = 0.634
i + j
// 0.734

val l: Float = 0.2F
val m: Double = 0.634
l + m
// 0.8340000029802322

val o = 1.2
val p = 0.4
o - p
// 0.7999999999999999

型の最大値以上、最小値以下の数値を代入することはできず、計算して実行した場合は数値が反転する。

val i: Int = 20000000000
// The integer literal does not conform to the expected type Int

val j: Int = 2147483647 + 1
println(j) // -2147483648

val k: Int = -2147483648 - 1
println(j) // 2147483647

・型推論
整数は基本Int型、少数の場合はDouble型が定義される

val i = 2
val j = 58
val k = -496
val l = 94568
// 全てInt型

val p = 10000000000
println(p::class.simpleName) // Long
// Intの最大値を超えるとLong型になる

val s = 100000000000000000000
// The value is out of range
// Long型より大きい数値は代入不可

val n = 0.1
val o = 0.0000043
// 基本Double型

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?