ios – Swift 2.0将1000格式化为友好的K.

我正在尝试编写一个函数来向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.我只是检查了双倍和它的地板是否相同.

在这个问题中找到了双重扩展:
Rounding a double value to x number of decimal places in swift

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...