如何在Swift中将小数格式化为百分比

时间:2019-08-22 23:33:20

标签: ios swift string floating-point double

我有一个函数,可以查找数组中相邻值的百分比差异。

var values =  [1.623,1.614,1.591,1.577,1.600,1.579,1.622]
    values.reverse()
let percentages = [0] + zip(values, values.dropFirst()).map {
     (old, new) in
    return (100.0 * (new - old) / old)
 }
  print(percentages)
  

[0.0,-2.651048088779294,1.3299556681444034,-1.4375000000000082,0.8877615726062151,1.445631678189826,0.5576208178438598]

有没有一种方法可以格式化我的值,使其看起来如下所示

  

[“ + 0.006%”,“ + 0.014%”,“ + 0.009%”,“-0.014%”,“ + 0.013%”,“-0.027%”]

3 个答案:

答案 0 :(得分:2)

例如,您可以以NumberFormatter开头...

let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.minimumIntegerDigits = 1
formatter.maximumIntegerDigits = 1
formatter.maximumFractionDigits = 3

var values =  [1.623,1.614,1.591,1.577,1.600,1.579,1.622]
values.reverse()
let percentages = [0] + zip(values, values.dropFirst()).map {
    (old, new) in
    return (100.0 * (new - old) / old)
}

print(percentages.compactMap { formatter.string(from: NSNumber(value: $0 / 100.0)) })

将打印类似....

["0%", "-2.651%", "1.33%", "-1.438%", "0.888%", "1.446%", "0.558%"]
  

您的字符串仅显示负数信号。这不是OP要求的。

?天堂禁止OP可能实际上必须做“某些”工作??

print(percentages.map { ($0 >= 0 ? "+" : "") + formatter.string(for: $0 / 100.0)! })

或者,最好是...

formatter.positivePrefix = "+"
//....
print(percentages.compactMap { formatter.string(for: $0 / 100.0) })

打印...

["+0%", "-2.651%", "+1.33%", "-1.438%", "+0.888%", "+1.446%", "+0.558%"]
  

如果可以的话,您能否进一步举例说明如何伪造数字?

该值的格式似乎与您所生成的值不匹配,例如0.8877615726062151将是0.8%,而不是0.009%,因此您需要进行一些自定义,最好通过稍微“混淆”这些值来完成。

所以,再次,从...开始

let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.minimumIntegerDigits = 1
formatter.maximumIntegerDigits = 1
formatter.maximumFractionDigits = 3
formatter.minimumFractionDigits = 3
formatter.positivePrefix = "+"

我修改了

print(percentages.compactMap { formatter.string(for: $0 / 100.0) })

print(percentages.compactMap { formatter.string(for: $0 / 10000.0) })

现在可以打印

["+0.000%", "-0.027%", "+0.013%", "-0.014%", "+0.009%", "+0.014%", "+0.006%"]

根据我的观察,这似乎是您的目标-您可以免费获得本地化

答案 1 :(得分:1)

只需在地图闭包中返回字符串

let percentages = [0] + zip(values, values.dropFirst()).map {      (old, new) in     
    let value = (100.0 * (new - old) / old)  
    return String(format: "%.3f%%", value)
}

答案 2 :(得分:1)

[0.0, -2.651048088779294, 1.3299556681444034, -1.4375000000000082, 0.8877615726062151, 1.445631678189826, 0.5576208178438598]
.map{String(format:"%+6.3f%%",$0/100)}

这将提供+/-号。