William Hu
William Hu

Reputation: 16141

swift how to convert Decimal type to String type

How to convert Decimal to String in swift?

For example

let de = Decimal(string: "123")

then how to convert de to String.

Upvotes: 21

Views: 31130

Answers (4)

Kyaw Zin Htun
Kyaw Zin Htun

Reputation: 1000

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

Upvotes: -3

Marco
Marco

Reputation: 1575

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

let decimalString = "\(de)"

Upvotes: 17

Chase Finch
Chase Finch

Reputation: 5451

Convert to NSDecimalNumber and use the stringValue.

NSDecimalNumber(decimal: de).stringValue

Upvotes: 10

Subhojit Mandal
Subhojit Mandal

Reputation: 450

Use an NSNumberFormatter to parse your input. Set its generatesDecimalNumbers property to true:

let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true

Here's how you use it, if you want to return 0 when the string can't be parsed:

func decimal(with string: String) -> NSDecimalNumber {
    return formatter.number(from: string) as? NSDecimalNumber ?? 0
}

decimal(with: "80.00")

// Result: 80 as an NSDecimalNumber

By default, the formatter will look at the device's locale setting to determine the decimal marker. You should leave it that way. For the sake of example, I'll force it to a French locale:

// DON'T DO THIS. Just an example of behavior in a French locale.
formatter.locale = Locale(identifier: "fr-FR")

decimal(with: "80,00")
// Result: 80

decimal(with: "80.00")
// Result: 0

If you really want to always use a comma as the decimal mark, you can set the decimalSeparator property:

formatter.decimalSeparator = ","

Upvotes: -3

Related Questions