在 Swift 中使用 NSNumberFormatter 格式化货币输入 [英] Formatting input for currency with NSNumberFormatter in Swift

查看:24
本文介绍了在 Swift 中使用 NSNumberFormatter 格式化货币输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a budget app that allows the user to input their budget as well as transactions. I need to allow the user to enter both pence and pounds from separate text fields and they need to be formatted together with currency symbols. I have this working fine at the moment but would like to make it localised as currently it only works with GBP. I have been struggling to convert NSNumberFormatter examples from Objective-C to Swift.

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

My first issue is the fact that I need to set the placeholders for the input fields to be specific to the users location. Eg. Pounds and Pence, Dollars and Cents etc...

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

The second issue is that the values inputted in each of the text fields such as 10216 and 32 need to be formatted and the currency symbol specific to the users location needs to be added. So it would become £10,216.32 or $10,216.32 etc...

另外,我需要在计算中使用格式化数字的结果.那么如何在不遇到货币符号问题的情况下做到这一点呢?

Also, I need to use the result of the formatted number in a calculation. So how can I do this without running into issues without running into issues with the currency symbol?

推荐答案

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

Here's an example on how to use it on Swift 3. ( Edit: Works in Swift 5 too )

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 上使用它的旧示例.


Here's the old example on how to use it on 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 中使用 NSNumberFormatter 格式化货币输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆