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