サンプルコード
DoubleExtension.swift
import Foundation
extension Double {
func toCurrency() -> String {
let subsidiaryCurrency: Int = 2 // 小数点以下の桁数
var rate: Double = 1
for _ in 0..<subsidiaryCurrency {
rate = rate * 10
}
let n: Double = floor(self * rate) / rate
let formatter: NumberFormatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.groupingSeparator = "," // カンマをつける
formatter.groupingSize = 3 // 何桁毎にカンマをつけるか決める
return formatter.string(from: n as NSNumber)!
}
}
使う
let num: Double = 1234.89
num.toCurrency() // 1,234.89