26
27

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 5 years have passed since last update.

[Swift]浮動小数点⇔文字列の変換

Last updated at Posted at 2015-01-22

以外と時間がかかったのでメモ。

  • Double型などの浮動小数点数値と文字列の相互変換は、String型では定義されていないため、NSString型を用いる必要がある

String --> Double(Float,Int,Int64,etc)

swift
let str: String = "3.3"

var dNum: Double = NSString(string: str).doubleValue   // 3.3
var fNum: Float  = NSString(string: str).floatValue    // 3.2999....
var iNum: Int    = NSString(string: str).integerValue  // 3
var lNum: Int64  = NSString(string: str).longLongValue // 3
var bNum: Bool   = NSString(string: str).boolValue     // true      

Double --> String

swift
let num = 3.33

var strf: String = NSString(format: "%.2f", num)
var strF: String = NSString(format: "%.2F", num)
var stre: String = NSString(format: "%.2e", num)
var strE: String = NSString(format: "%.2E", num)
var strg: String = NSString(format: "%.2g", num)
var strG: String = NSString(format: "%.2G", num)

参考

  • 整数Int⇔文字列Stringの相互変換は、String型にて定義されている

Int --> String

swift
let num: Int = 3
var str: String = String(num)

String --> Int

swift
let str: String = "3"
var num: Int? = str.toInt()
26
27
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
26
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?