LoginSignup
1
2

More than 3 years have passed since last update.

Swift文字列←→CGFloatやり方によっては誤差が含まれたまま文字列に変換されてしまう

Last updated at Posted at 2020-06-23

Swift文字列←→CGFloatやり方によっては誤差が含まれたまま文字列に変換されてしまう

目的:"1.1"をCGFloatに変換して、変換したCGFloatの値をもとの文字列"1.1"に戻したい

  1. 文字列からCGFloatに変換
  2. CGFloatから文字列に変換

誤差が含まれて文字列になってしまうやり方があることがわかった
"1.1"をfloatへ(1.100000023841858)これをCGFloatに変換してから文字列へ"1.100000023841858"
32bitアプリか64bitアプリかで違うということらしいので、64bitのCGFloatはdoubleのtypedef

// CGFloatより
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.

ここで注意して欲しいのは、CGFloat(Float("1.1"))としないこと、これは32bitアプリの場合
現在は64bitアプリなのでCGFloat(Double("1.1"))が正解

CGFloatへの変換はNumberFormatterクラスを使う
  • NumberFormatterクラスを使う
    これを使うといい
let strNum = "1.1"
let numberFormatter = NumberFormatter().number(from: strNum) ?? 0.0
let cgFloat = CGFloat(truncating: numberFormatter)
let str = "\(cgFloat)"
1
2
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
2