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?

SwiftのFloat・Double・Decimalの違いと使い分け

0
Posted at

SwiftのFloat・Double・Decimalの違いと使い分け

〜金融計算・UI表示・精度の罠まで徹底解説〜

1. はじめに

  • 本記事の目的:よく混乱しがちな数値型の違いを明確に整理する
  • 対象読者:Swift初級〜中級の方(業務経験1〜2年目など)
  • なぜ知っておくべきか? → 精度トラブル・パフォーマンス問題を防ぐため

2. 各数値型の基本情報

型名 精度 桁数 主な用途 特徴
Float 約6〜7桁 32bit 軽量な3D・UI演算 精度は低いが処理が高速
Double 約15〜16桁 64bit 数学計算の標準 精度と速度のバランスが良い
Decimal 最大38桁(10進) 任意精度 金融・税金など精度重視 精度が高く、処理はやや重い

※ Swiftの数値リテラル(例: 1.0)はデフォルトで Double 型になります。


3. 計算精度の違い(サンプルコード付き)

❌ Doubleの誤差例

let d: Double = 0.1 + 0.2
print(d) // → 0.30000000000000004

✅ Decimalでの正確な計算

let a = Decimal(string: "0.1")!
let b = Decimal(string: "0.2")!
let sum = a + b
print(sum) // → 0.3

4. 各型の使い分け【実務視点】

シチュエーション 推奨型 理由
UIアニメーション・3D演算 Float 処理速度が求められるため
一般的な数値演算
JSON/APIから受け取る数値
Double 精度と速度のバランスが良く標準型
金額・金利・税計算など Decimal 精度重視、端数処理・誤差回避が必要なため

5. よくある落とし穴と注意点

  1. Double の比較に == を使わない
  2. Decimal 同士でも Double との混在で精度ズレが起きる
  3. Decimal は NSDecimalNumber とは別物(使い分けに注意)

6. まとめ

  • Float・Double・Decimal には明確な違いがある
  • 処理速度と精度のバランスを見て選択することが重要
  • 金融・会計用途では Decimal 一択
    精度の問題は見落とされやすいバグの温床なので意識的に設計しよう
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?