랭귀지/SWIFT
Swift 숫자값을 3자리 단위로 콤마(,)를 추가
유키공
2018. 2. 7. 13:00
가끔 숫자값을 3자리 단위로 콤마(,)를 추가하여 자릿수를 구분해주는 기능이 필요할 경우
extension Int { var withComma: String { let decimalFormatter = NumberFormatter() decimalFormatter.numberStyle = NumberFormatter.Style.decimal decimalFormatter.groupingSeparator = "," decimalFormatter.groupingSize = 3 return decimalFormatter.string(from: self as NSNumber)! } } extension String { var delComma: String { if self.characters.count > 0 { return self.replacingOccurrences(of: ",", with: "") } else { return "0" } } }사용하기
let a: String = (123456789).withComma let b: String = a.delComma let c: String = "123,45a".delComma