LoginSignup
3
2

More than 3 years have passed since last update.

数値の丸め方について

Posted at

数値を丸めたい!

UISliderのvalueを取得した際、小数第5位まで表示されてしまったため数値の丸め方についてまとめました。

方法1 formatを使用する

howToChangeDigits
let number = 12.34567

print(String(format: "%.0f", number))   // -> "12"
print(String(format: "%.1f", number))   // -> "12.3"
print(String(format: "%.2f", number))   // -> "12.35"
print(String(format: "%.3f", number))   // -> "12.346"

結果より、四捨五入して丸められていることがわかります。
丸めた後のデータ型は、String型になります。

方法2 round()を使用する

howToChangeDigits
let number = 12.34567

print(round(number)                  // -> 12.0
print(round(number * 10) / 10)       // -> 12.3
print(round(number * 100) / 100)     // -> 12.35
print(round(number * 1000) / 1000)   // -> 12.346

formatを使用した時と同様に四捨五入されます。
丸めた後のデータ型はDouble型またはFloat型になります。特に型を指定せずにnumberを定義した場合はDouble型になります。
round()の代わりにfloor()を使用すると切り捨て、ceil()を使用すると切り上げて丸めることができます。

参考サイト
3
2
1

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