Swiftで文字列をDouble型に変換する

2021年11月16日

環境
Swift version 5.2.3
書式
Double( 文字列 )
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let cftA = "9876.543210"
let resA = Double(cftA)
print(resA ?? "nil")
// 数値に変換できない場合は、nil を返す
let cftB = "test"
let resB = Double(cftB)
print(resB ?? "nil")
// アンラップすると安全
let cftC = "98765.43210"
if let resC = Double(cftC) {
print(resC)
}else{
print("double数値に変換できません")
}
let cftA = "9876.543210" let resA = Double(cftA) print(resA ?? "nil") // 数値に変換できない場合は、nil を返す let cftB = "test" let resB = Double(cftB) print(resB ?? "nil") // アンラップすると安全 let cftC = "98765.43210" if let resC = Double(cftC) { print(resC) }else{ print("double数値に変換できません") }
let cftA = "9876.543210"
let resA  = Double(cftA)
print(resA ?? "nil")

// 数値に変換できない場合は、nil を返す
let cftB = "test"
let resB = Double(cftB)
print(resB ?? "nil")

// アンラップすると安全
let cftC = "98765.43210"
if let resC = Double(cftC) {
    print(resC)
}else{
    print("double数値に変換できません")
}

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
9876.54321
nil
98765.4321
9876.54321 nil 98765.4321
9876.54321
nil
98765.4321

 

Swift

Posted by arkgame