gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:47:56 25 4
gpt4 key购买 nike

我正在创建一个预算应用程序,允许用户输入预算和交易。我需要允许用户从单独的文本字段输入便士和英镑,并且它们需要与货币符号一起格式化。我目前工作正常,但希望将其本地化,因为目前它仅适用于英镑。我一直在努力将 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/48628500/

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