我在格式化iOS Swift中的double变量时遇到了问题
我拥有的变量类似于0.7, -4.56, 34.6
,但它们的格式应为00.70, -04.56, 34.60
解决这个问题的最佳方法是什么?
答案 0 :(得分:2)
签出此
extension Double {
func formatNumber(minimumIntegerDigits: Int, minimumFractionDigits: Int, maximumFractionDigits: Int=2) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumIntegerDigits = minimumIntegerDigits
numberFormatter.minimumFractionDigits = minimumFractionDigits
numberFormatter.maximumFractionDigits = maximumFractionDigits
return numberFormatter.string(for: self) ?? ""
}
}
999.989.formatNumber(minimumIntegerDigits: 2, minimumFractionDigits: 2) // => 999.99
9.989.formatNumber(minimumIntegerDigits: 2, minimumFractionDigits: 2) // => 09.99
答案 1 :(得分:0)
像这样使用NumberFormatter
:
let number = 0.7
let numberFormatter = NumberFormatter()
numberFormatter.minimumIntegerDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
numberFormatter.string(for: number)
或者将其定义为函数:
func format(_ x: Double) -> String? {
guard abs(x) < 100 else {
print("The argument must have 2 integer digits at maximum")
return nil
}
let numberFormatter = NumberFormatter()
numberFormatter.maximumIntegerDigits = 2
numberFormatter.minimumIntegerDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
return numberFormatter.string(for: x)
}
format(-0.7) //"-00.70"
format(120) //nil , and prints "The argument must have 2 integer digits at maximum"
请记住,方法Formatter.string(for:)
返回一个可选字符串。
@LeoDabus指出,为避免每次调用此函数时都创建一个新的Number Formatter,我们可以在NumberFormatter上定义一个静态属性:
extension NumberFormatter {
static let formatter_2Int_2Frac: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.maximumIntegerDigits = 2
numberFormatter.minimumIntegerDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
return numberFormatter
}()
}
因此,上面的函数将如下所示:
func format(_ x: Double) -> String? {
guard abs(x) < 100 else {
print("The argument must have 2 integer digits at maximum")
return nil
}
return NumberFormatter.formatter_2Int_2Frac.string(for: x)
}
答案 2 :(得分:0)
另一个选择
let f = NumberFormatter()
f.minimumFractionDigits = 2
f.minimumIntegerDigits = 2
let str = f.string(from:-4.6)
print(str) // -04.60
答案 3 :(得分:0)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumIntegerDigits = 2
numberFormatter.minimumFractionDigits = 2
let formattedNumbers = [0.7, -4.56, 34.6].flatMap { number in
return numberFormatter.string(for: number)
}
print(formattedNumbers) //prints ["00.70", "-04.56", "34.60"]