How to convert Decimal to String with two digits after separator?

前端 未结 2 1655
囚心锁ツ
囚心锁ツ 2021-01-16 04:46

This is what I do now:

extension Decimal {
    var formattedAmount: String {
        let formatter = NumberFormatter()
        formatter.generatesDecimalNumbers =         


        
相关标签:
2条回答
  • 2021-01-16 04:59

    This:

    formatter.string(from: ...) // requires a NSNumber
    

    You can either do this:

    formatter.string(for: self) // which takes Any as argument
    

    Or:

    string(from: self as NSDecimalNumber) // cast self to NSDecimalNumber
    
    0 讨论(0)
  • 2021-01-16 05:04

    This should work

    extension Decimal {
        var formattedAmount: String? {
            let formatter = NumberFormatter()
            formatter.generatesDecimalNumbers = true
            formatter.minimumFractionDigits = 2
            formatter.maximumFractionDigits = 2
            return formatter.string(from: self as NSDecimalNumber)
        }
    }
    
    0 讨论(0)
提交回复
热议问题