ios 如何将 Double 格式化为货币 - Swift 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41558832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format a Double into Currency - Swift 3
提问by Gar
I'm new to Swift programming and I've been creating a simple tip calculator app in Xcode 8.2, I have my calculations set up within my IBAction
below. But when I actually run my app and input an amount to calculate (such as 23.45), it comes up with more than 2 decimal places. How do I format it to .currency
in this case?
我是 Swift 编程的新手,我一直在 Xcode 8.2 中创建一个简单的小费计算器应用程序,我在IBAction
下面设置了我的计算。但是当我实际运行我的应用程序并输入要计算的数量(例如 23.45)时,它会出现超过 2 个小数位。.currency
在这种情况下如何将其格式化?
@IBAction func calculateButtonTapped(_ sender: Any) {
var tipPercentage: Double {
if tipAmountSegmentedControl.selectedSegmentIndex == 0 {
return 0.05
} else if tipAmountSegmentedControl.selectedSegmentIndex == 1 {
return 0.10
} else {
return 0.2
}
}
let billAmount: Double? = Double(userInputTextField.text!)
if let billAmount = billAmount {
let tipAmount = billAmount * tipPercentage
let totalBillAmount = billAmount + tipAmount
tipAmountLabel.text = "Tip Amount: $\(tipAmount)"
totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)"
}
}
回答by silicon_valley
You can use this string initializer if you want to force the currency to $:
如果要强制货币为 $,可以使用此字符串初始值设定项:
String(format: "Tip Amount: $%.02f", tipAmount)
If you want it to be fully dependent on the locale settings of the device, you should use a NumberFormatter
. This will take into account the number of decimal places for the currency as well as positioning the currency symbol correctly. E.g. the double value 2.4 will return "2,40?" for the es_ES locale and "¥?2" for the jp_JP locale.
如果您希望它完全依赖于设备的区域设置,您应该使用NumberFormatter
. 这将考虑货币的小数位数以及正确定位货币符号。例如双精度值 2.4 将返回“2,40?” 对于 es_ES 语言环境和“¥?2”对于 jp_JP 语言环境。
let formatter = NumberFormatter()
formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already
formatter.numberStyle = .currency
if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) {
tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)"
}
回答by Camilo Ortegón
How to do it in Swift 4:
如何在 Swift 4 中做到这一点:
let myDouble = 9999.99
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = Locale.current
// We'll force unwrap with the !, if you've got defined data you may need more error checking
let priceString = currencyFormatter.string(from: NSNumber(value: myDouble))!
print(priceString) // Displays ,999.99 in the US locale
回答by Chung Nguyen
You can to convert like that: this func convert keep for you maximumFractionDigits whenever you want to do
你可以这样转换:这个 func convert 为你保留 maximumFractionDigits 每当你想做的时候
static func df2so(_ price: Double) -> String{
let numberFormatter = NumberFormatter()
numberFormatter.groupingSeparator = ","
numberFormatter.groupingSize = 3
numberFormatter.usesGroupingSeparator = true
numberFormatter.decimalSeparator = "."
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
return numberFormatter.string(from: price as NSNumber)!
}
i create it in class Model then when you call , you can accecpt it another class , like this
我在 Model 类中创建它然后当你打电话时,你可以接受另一个类,像这样
print("InitData: result convert string " + Model.df2so(1008977.72))
//InitData: result convert string "1,008,977.72"
回答by Duncan C
The best way to do this is to create an NSNumberFormatter
. (NumberFormatter
in Swift 3.) You can request currency and it will set up the string to follow the user's localization settings, which is useful.
最好的方法是创建一个NSNumberFormatter
. (NumberFormatter
在 Swift 3 中。)您可以请求货币,它会设置字符串以遵循用户的本地化设置,这很有用。
If you want to force a US-formatted dollars and cents string you can format it this way:
如果您想强制使用美国格式的美元和美分字符串,您可以通过以下方式对其进行格式化:
let amount: Double = 123.45
let amountString = String(format: "$%.02f", amount)
回答by Rob
In addition to the NumberFormatter
or String(format:)
discussed by others, you might want to consider using Decimal
or NSDecimalNumber
and control the rounding yourself, thereby avoid floating point issues. If you're doing a simple tip calculator, that probably isn't necessary. But if you're doing something like adding up the tips at the end of the day, if you don't round the numbers and/or do your math using decimal numbers, you can introduce errors.
除了其他人讨论的NumberFormatter
or之外String(format:)
,您可能需要考虑使用Decimal
orNSDecimalNumber
并自己控制舍入,从而避免浮点问题。如果您正在做一个简单的小费计算器,那可能没有必要。但是,如果您要在一天结束时将小费相加,如果您没有对数字进行四舍五入和/或使用十进制数字进行数学运算,则可能会引入错误。
So, go ahead and configure your formatter:
所以,继续配置你的格式化程序:
let formatter: NumberFormatter = {
let _formatter = NumberFormatter()
_formatter.numberStyle = .decimal
_formatter.minimumFractionDigits = 2
_formatter.maximumFractionDigits = 2
_formatter.generatesDecimalNumbers = true
return _formatter
}()
and then, use decimal numbers:
然后,使用十进制数:
let string = "2.03"
let tipRate = Decimal(sign: .plus, exponent: -3, significand: 125) // 12.5%
guard let billAmount = formatter.number(from: string) as? Decimal else { return }
let tip = (billAmount * tipRate).rounded(2)
guard let output = formatter.string(from: tip as NSDecimalNumber) else { return }
print("\(output)")
Where
在哪里
extension Decimal {
/// Round `Decimal` number to certain number of decimal places.
///
/// - Parameters:
/// - scale: How many decimal places.
/// - roundingMode: How should number be rounded. Defaults to `.plain`.
/// - Returns: The new rounded number.
func rounded(_ scale: Int, roundingMode: RoundingMode = .plain) -> Decimal {
var value = self
var result: Decimal = 0
NSDecimalRound(&result, &value, scale, roundingMode)
return result
}
}
Obviously, you can replace all the above "2 decimal place" references with whatever number is appropriate for the currency you are using (or possibly use a variable for the number of decimal places).
显然,您可以使用适合您使用的货币的任何数字替换上述所有“小数点后两位”引用(或者可能使用一个变量来表示小数位数)。
回答by king_T
you can create an Extension for either string or Int, I would show an example with String
您可以为字符串或 Int 创建扩展,我将展示一个带有字符串的示例
extension String{
func toCurrencyFormat() -> String {
if let intValue = Int(self){
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "ig_NG")/* Using Nigeria's Naira here or you can use Locale.current to get current locale, please change to your locale, link below to get all locale identifier.*/
numberFormatter.numberStyle = NumberFormatter.Style.currency
return numberFormatter.string(from: NSNumber(value: intValue)) ?? ""
}
return ""
}
}
回答by Muhammad Zeeshan
extension String{
func convertDoubleToCurrency() -> String{
let amount1 = Double(self)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
numberFormatter.locale = Locale(identifier: "en_US")
return numberFormatter.string(from: NSNumber(value: amount1!))!
}
}
回答by KkMIW
extension Float {
var localeCurrency: String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = .current
return formatter.string(from: self as NSNumber)!
}
}
amount = 200.02
print("Amount Saved Value ",String(format:"%.2f", amountSaving. localeCurrency))
For me Its return 0.00! Looks to me Extenstion Perfect when accessing it return 0.00! Why?
对我来说它的回报是 0.00!在我看来,Extenstion Perfect 在访问它时返回 0.00!为什么?
回答by Atharva Vaidya
Here's how:
就是这样:
let currentLocale = Locale.current
let currencySymbol = currentLocale.currencySymbol
let outputString = "\(currencySymbol)\(String(format: "%.2f", totalBillAmount))"
1st line: You're getting the current locale
第一行:您正在获取当前语言环境
2nd line: You're getting the currencySymbol for that locale. ($, £, etc)
第 2 行:您将获得该语言环境的货币符号。($、£ 等)
3rd line: Using the format initializer to truncate your Double to 2 decimal places.
第 3 行:使用格式初始值设定项将您的 Double 截断为 2 个小数位。