1
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?

More than 1 year has passed since last update.

【Android】Mathクラスについてpart1【Kotlin】

Last updated at Posted at 2023-09-10

はじめに

今回はabsメソッドという 絶対値を返すメソッドに出会いそこからMathクラスを見つけたので、それについて特に使いそうなものをまとめておく為に記事を書きます。

説明

abs()

abs(-1)   // 1

abs()は Int,Long,Float,Double の好きな型で絶対値を返します。

floor()

floor(1.111)   // 1.0

小数点以下を切り捨て

ceil()

ceil(1.111)   // 2.0

小数点以下を切り上げ

round()

round(11.4)   // 11
round(11.5)   // 12

round(12.4)   // 12
round(12.5)   // 12

round(12.6)   // 13

round() は 小数点以下を四捨五入と勘違いしがちですが、厳密には違うらしく整数の整数の一の位が奇数か偶数かによって小数点以下を四捨五入するか切り捨てるかが変わるみたいです。
整数の一の位が奇数の場合 4以下を切り捨て、5以上を切り上げ(四捨五入)
整数の一の位が偶数の場合 5以下を切り捨て、6以上を切り上げ

この方法を 「銀行丸め」 「最近接丸め」 「JIS丸め」などというらしく、詳しくはそれぞれ調べてもらえればと思いうます。

roundToInt()

10.4.roundToInt()   // 10
10.5.roundToInt() //   11

四捨五入して Intにする

10.4.roundToLong()

10.4.roundToLong() //   10
10.5.roundToLong() //   11

四捨五入して Longにする

参考

1
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
1
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?