Swift5でDoubleをInt、Float、String、NSNumber、Dataに変換する方法
Double(整数)をInt(数値)、Float、String(文字列)、NSString、NSNumber、Data、NSDataに変換する方法をまとめました。
Double ←→ Int
Doble → Int
var double Num : Doble = 1234.5
var intNum : Int = Int(doubleNum)
Int → Double
var intNum : Int = 1234
var doubleNum : Double = Double(intNum)
Double ←→ Float
Double → Float
var doubleNum : Double = 1.234567890
var floatNum : Float = Float(doubleNum)
桁あふれは四捨五入になる→1.2345679
Float → Double
var floatNum : Float = 1.234567890
var doubleNum : Double = Double(floatNum)
桁あふれの場合、少しずれる → 1.2345678806304932
Double ←→ String
Double → String
var num : Double = 1234.5
var str : String = String(num)
String → Float
var str : String = "1234.5"
var nsstring : NSString = NSString(string: str)
var num : Double = nsstring.doubleValue
Double ←→ NSString
Double → NSString
var doubleNum : Doble = 1.2345678
var str : String = String(doubleNum)
var nsstr: NSString = NSString(string: str)
NSString → Double
var nsstring : NSString = NSString(string: "1.2345678")
var doubleNum : Double = nsstring.doubleValue
Double ←→ NSNumbar
Double → NSNumbar
var doubleNum = 1.2345678
var num = NSNumber.init(value: doubleNum)
NSNumbar → Double
var num = NSNumber.init(value: 1.2345678)
var doubleNum = num.doubleValue
Double ←→ Data
Double → Data
var dobleNum : Doble = 1.2345678
var str : String = String(dobleNum)
var data : Data = str.data(using: .utf8)!
Data → Double
var data : Data = "1.2345678".data(using: .utf8)!
var str : String = String.init(data: data, encoding: .utf8)!
var doubleNum : Double = Double(str)!
Double ←→ NSData
Double → NSData
var doubleNum : Doble = 1.2345678
var str : String = String(doubleNum)
var data : Data = str.data(using: .utf8)!
var nsdata : NSData = NSData.init(data: data)
NSData → Double
var data : Data = "1.2345678".data(using: String.Encoding.utf8)!
var nsdata : NSData = NSData.init(data: data)
var str : String = String.init(data: nsdata as! Data, encoding: .utf8)!
var doubleNum : Double = Double(str)!