2
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.

Kotlin, Swiftで小数点以下の四捨五入をする方法

Posted at

概要

Kotlin, Swiftで小数点以下の四捨五入をしたいときがあった。
調べればやり方はすぐ出てくるが、自分用の忘備録としてまとめておく。
ちなみにKotlin, Swiftどちらでもコードはほぼ同じ。

小数点以下の四捨五入をする方法

Kotlin

val number:Float = 1.23456
val num1 = Math.round(number)                     // 小数第1位四捨五入 : 1
val num2 = Math.round(number * 10.0) / 10.0       // 小数第2位四捨五入 : 1.2
val num3 = Math.round(number * 100.0) / 100.0     // 小数第3位四捨五入 : 1.23
val num4 = Math.round(number * 1000.0) / 1000.0   // 小数第4位四捨五入 : 1.235

Swift

let number:Float = 1.23456
let num1 = round(number)                     // 小数第1位四捨五入 : 1
let num2 = round(number * 10.0) / 10.0       // 小数第2位四捨五入 : 1.2
let num3 = round(number * 100.0) / 100.0     // 小数第3位四捨五入 : 1.23
let num4 = round(number * 1000.0) / 1000.0   // 小数第4位四捨五入 : 1.235
2
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
2
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?