我正在尝试编写一个函数,以呈现成千上万个K和M。例如:
1000 = 1k
1100 = 1.1k
15000 = 15k
115000 = 115k
1000000 = 1m
这是我到目前为止的去处:
func formatPoints(num: Int) -> String {
let newNum = String(num / 1000)
var newNumString = "\(num)"
if num > 1000 && num < 1000000 {
newNumString = "\(newNum)k"
} else if num > 1000000 {
newNumString = "\(newNum)m"
}
return newNumString
}
formatPoints(51100) // THIS RETURNS 51K instead of 51.1K
我如何才能使用此功能,我想念什么?
func formatPoints(num: Double) ->String{
let thousandNum = num/1000
let millionNum = num/1000000
if num >= 1000 && num < 1000000{
if(floor(thousandNum) == thousandNum){
return("\(Int(thousandNum))k")
}
return("\(thousandNum.roundToPlaces(1))k")
}
if num > 1000000{
if(floor(millionNum) == millionNum){
return("\(Int(thousandNum))k")
}
return ("\(millionNum.roundToPlaces(1))M")
}
else{
if(floor(num) == num){
return ("\(Int(num))")
}
return ("\(num)")
}
}
extension Double {
/// Rounds the double to decimal places value
func roundToPlaces(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(self * divisor) / divisor
}
}
如果数字为整数,则更新的代码现在不应返回.0。例如,现在应该输出1k而不是1.0k。我只是基本上检查了double和它的底楼是否相同。
我在此问题中找到了双精度扩展名:快速将双精度值四舍五入为x的小数位数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句