How to format a Numeric value in Swift with Currency symbol and Decimal Precision

Use NumberFormatter - A formatter that converts between numeric values and their textual representations.

import UIKit

extension Formatter {
    static let withDecimalSeparator: NumberFormatter = {
        
        let formatter = NumberFormatter()
        formatter.groupingSeparator = "_"
        formatter.decimalSeparator = "."
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        formatter.numberStyle = .decimal
        
        return formatter
    }()
    
    static let withCurrencySeparator: NumberFormatter = {
        
        let formatter = NumberFormatter()
        formatter.currencySymbol = "$"
        formatter.decimalSeparator = "."
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        formatter.numberStyle = .currency
        
        return formatter
    }()
}

extension Double {
    var formattedWithSeparator1: String {
        return Formatter.withDecimalSeparator.string(for: self) ?? ""
    }
    var formattedWithSeparator2: String {
        return Formatter.withCurrencySeparator.string(for: self) ?? ""
    }
}

var myString = "123456.1149"
var myDouble : Double = Double(myString) ?? 0
print(myDouble.formattedWithSeparator1)
//Result = 123_456.11
print(myDouble.formattedWithSeparator2)
//Result = $123,456.11

myString = "123456.1150"
myDouble = Double(myString) ?? 0
print(myDouble.formattedWithSeparator1)
//Result = 123_456.12
print(myDouble.formattedWithSeparator2)
//Result = $123,456.12

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.