简体   繁体   English

如何将NSDecimalNumber格式化为Swift字符串?

[英]How can I format an NSDecimalNumber into a Swift string?

If you have code such as this, then result will be "2.99": 如果您有这样的代码,则result将为“ 2.99”:

let n = 2.99
let result = String(format: "%.2f", n)

However, if you have code like this: 但是,如果您有这样的代码:

    let nNS:NSDecimalNumber = 2.99
    let result2 = String(format: "%.2f", nNS)

Then result2 is "0.00". 那么result2为“ 0.00”。

How can you format an NSDecimalNumber into a string like this? 如何将NSDecimalNumber格式化为这样的字符串?

You can use a NumberFormatter to convert an NSNumber to a String. 您可以使用NumberFormatterNSNumber转换为字符串。

let priceNS:NSDecimalNumber = 2.99
let nf = NumberFormatter()
nf.maximumFractionDigits = 2
nf.string(from: priceNS) //2.99

You should format your product price using NumberFormatter and use your product locale: https://developer.apple.com/documentation/storekit/skproduct/1506094-price 您应该使用NumberFormatter格式化产品价格并使用产品区域设置: https : //developer.apple.com/documentation/storekit/skproduct/1506094-price

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency 
numberFormatter.locale = someSKProduct.priceLocale
let formattedPrice = numberFormatter.string(from: someSKProduct.price) ?? ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM