Swift如何使用千位分隔符格式化大量数字?

时间:2015-03-09 06:46:40

标签: swift

是否有简单的命令将1.60543e + 06格式化为1,605,436 ???

resultFV.text = String.localizedStringWithFormat(“%f”,fv)

没有得到它。

7 个答案:

答案 0 :(得分:32)

在Swift 3中,

NumberFormatter.localizedString(from: NSNumber(value: whatever), number: NumberFormatter.Style.decimal)

答案 1 :(得分:21)

Swift Xcode 6.3,已解决(我决定在代码中保留$)。如果您不想在输出中使用$,请将.CurrencyStyle更改为.DecimalStyle

var fv = 3534234.55 
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0;
resultFV.text = formatter.stringFromNumber(fv) // result: $3,534,235 –

答案 2 :(得分:19)

您应该使用NumberFormatter

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal

resultFV.text = numberFormatter.string(from: fv)

答案 3 :(得分:7)

更新Swift 4.1货币字符串:

let balance = 1234567

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 0

let result = formatter.string(from: NSNumber(value: balance)) 
// result: $1,234,567

您可以将formatter.numberStyle更改为.decimal,将其保留为不带“$”符号的数字。

答案 4 :(得分:6)

您可以通过在Swift 3 +中使用String初始化器来实现此目的:

// 1605436
let value: Int = 1605436

// "1,605,436" where Locale == en_US
let formattedInt = String(format: "%d", locale: Locale.current, value) 

// "1,605,436" where Locale == en_US
let formattedDouble = String(format: "%.0f", locale: Locale.current, Double(value))

答案 5 :(得分:4)

为什么不限制精度,例如".0f"

resultFV.text = String.localizedStringWithFormat("%.0f", fv)

更新答案:

var formatter: NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle;
var formattedStr: NSString = formatter.stringFromNumber(NSNumber(double: fv))!
resultFV.text = formattedStr

答案 6 :(得分:0)

Swift 5更新

var unformattedValue : Double = 3534234.55
var formatter = NumberFormatter()
formatter.numberStyle = .currency // or .decimal if desired
formatter.maximumFractionDigits = 2; //change as desired
formatter.locale = Locale.current // or = Locale(identifier: "de_DE"), more locale identifier codes: https://gist.github.com/jacobbubu/1836273
var displayValue : String = formatter.string(from: NSNumber(value: unformattedValue))! // displayValue: "$3,534,235" ```