Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active April 8, 2022 07:49
Show Gist options
  • Save TuenTuenna/ab4eb7f73607017941008592728681a4 to your computer and use it in GitHub Desktop.
Save TuenTuenna/ab4eb7f73607017941008592728681a4 to your computer and use it in GitHub Desktop.
Swift 천단위 숫자 포매터

넘버 포매터

extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.groupingSeparator = "," // 천 단위마다 , 콤마 넣어주기
        return formatter
    }()
}

숫자 -> 문자열로 만들기 위한 Numeric 익스텐션

extension Numeric {
    var formattedWithSeparator: String { Formatter.withSeparator.string(for: self) ?? "" }
}

사용 예시

2358000.formattedWithSeparator  // "2,358,000"
2358000.99.formattedWithSeparator  // "2,358,000.99"

출처

https://stackoverflow.com/questions/29999024/adding-thousand-separator-to-int-in-swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment