【问题标题】:convert number price swift [closed]快速转换数字价格[关闭]
【发布时间】:2021-02-19 11:11:23
【问题描述】:

我必须在标签的文本中显示价格。公共变量余额:浮动 仅作为一个数字,我得到一个“8000”而不是它应该显示“80.00 €”。我不能转换它你能帮我吗?

public var balance: Float
    saldoPrice.text = String(userDataByCode!.balance)

以这种方式显示“8000”

【问题讨论】:

标签: ios swift numbers


【解决方案1】:

我创建了以下扩展来解决您的特定问题:

extension Double{
     func formatToAmount() -> String{
        let numberFormatter = NumberFormatter()
        numberFormatter.groupingSeparator = ","
        numberFormatter.groupingSize = 3
        numberFormatter.usesGroupingSeparator = true
        numberFormatter.decimalSeparator = "."
        numberFormatter.numberStyle = .decimal
        numberFormatter.maximumFractionDigits = 2
        
        let value = self.roundToDecimal(2)
        
        var res = numberFormatter.string(from: value as NSNumber)!
        if !res.contains("."){
            res += ".00"
        }else{
            let resAfterComma = String(res.split(separator: ".")[1])
            if resAfterComma.count == 1{  res += "0" }
        }
        res += " €"
        return res
    }

    func roundToDecimal(_ fractionDigits: Int) -> Double {
        let multiplier = pow(10, Double(fractionDigits))
        return Darwin.round(self * multiplier) / multiplier
    }
}

用法:

var yourNumber : Double = 80
yourNumber.formatToAmount() // prints: 80.00 €

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2019-07-20
    • 2023-01-21
    • 1970-01-01
    相关资源
    最近更新 更多