gpt4 book ai didi

swift - 在 Swift 中使用 NSNumberFormatter 格式化货币输入

转载 作者:IT王子 更新时间:2023-10-29 04:57:19 26 4
gpt4 key购买 nike

我正在创建一个预算应用程序,允许用户输入他们的预算和交易。我需要允许用户从单独的文本字段中输入便士和英镑,并且需要将它们与货币符号一起格式化。我目前可以很好地使用它,但希望将其本地化,因为目前它仅适用于 GBP。我一直在努力将 NSNumberFormatter 示例从 Objective-C 转换为 Swift。

我的第一个问题是我需要将输入字段的占位符设置为特定于用户位置。例如。英镑和便士、美元和美分等...

第二个问题是在每个文本字段中输入的值(例如 10216 和 32)需要进行格式化,并且需要添加特定于用户位置的货币符号。所以它会变成 10,216.32 英镑或 10,216.32 美元等......

此外,我需要在计算中使用格式化数字的结果。那么,如何在不遇到货币符号问题的情况下执行此操作?

最佳答案

这是一个关于如何在 Swift 3 上使用它的例子。(编辑:也适用于 Swift 5)

let price = 123.436 as NSNumber

let formatter = NumberFormatter()
formatter.numberStyle = .currency
// formatter.locale = NSLocale.currentLocale() // This is the default
// In Swift 4, this ^ was renamed to simply NSLocale.current
formatter.string(from: price) // "$123.44"

formatter.locale = Locale(identifier: "es_CL")
formatter.string(from: price) // $123"

formatter.locale = Locale(identifier: "es_ES")
formatter.string(from: price) // "123,44 €"

这是关于如何在 Swift 2 上使用它的旧示例。

let price = 123.436

let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
// formatter.locale = NSLocale.currentLocale() // This is the default
formatter.stringFromNumber(price) // "$123.44"

formatter.locale = NSLocale(localeIdentifier: "es_CL")
formatter.stringFromNumber(price) // $123"

formatter.locale = NSLocale(localeIdentifier: "es_ES")
formatter.stringFromNumber(price) // "123,44 €"

关于swift - 在 Swift 中使用 NSNumberFormatter 格式化货币输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24960621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com