swift how to convert Decimal type to String type

Viewed 21528

How to convert Decimal to String in swift?

For example

let de = Decimal(string: "123")

then how to convert de to String.

4 Answers

Leveraging the fact that Decimal conforms to protocol CustomStringConvertible I would simply do:

let decimalString = "\(de)"

Convert to NSDecimalNumber and use the stringValue.

NSDecimalNumber(decimal: de).stringValue

In Swift 3 and above try this

extension Formatter {
    static let stringFormatters: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .none
        return formatter
    }()
}

extension Decimal {
    var formattedString: String {
        return Formatter.stringFormatters.string(for: self) ?? ""
    }
}

you can show like this

label.text = someDecimal.formattedString
Related