草庐IT

iOS swift : Formatting a custom Currency Number

coder 2023-09-09 原文

用逗号分隔符格式化大数。

已解决(代码已更新且完全可用)

晚上,我有一个来自 Double 的类型别名 Currency

我想用千位之间的逗号打印它。

这是我做的:

import Foundation

typealias Currency = Double

extension Currency {
    var credit: Double { return self }
    var usd: Double { return self * 0.62 }
    
    func description() -> String {
        let price = self as NSNumber
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        return formatter.string(from: price)!
    }
    
}

let price: Currency = 1000000000

print(price.description) 
/* It doesn't work, I want something like 1000,000,000.0 */

但它不起作用。怎么了? ?

最佳答案

description 是通过 CustomStringConvertible 协议(protocol)嵌入 Foundation 的属性,该协议(protocol)将 description 变量声明为:

A textual representation of the value.

您要调用您的description() 方法。添加括号,你会得到你想要的结果:

price.description()

关于iOS swift : Formatting a custom Currency Number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40248726/

有关iOS swift : Formatting a custom Currency Number的更多相关文章

随机推荐