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

Ben*_*Nov 14 format numbers ios swift swift2

我正在尝试编写一个函数来向K和M提供数千和数百万例如:

1000 = 1k
1100 = 1.1k
15000 = 15k
115000 = 115k
1000000 = 1m
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的地方:

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
Run Code Online (Sandbox Code Playgroud)

如何让这个功能起作用,我缺少什么?

use*_*203 19

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
    }
}
Run Code Online (Sandbox Code Playgroud)

如果数字是完整的,更新的代码现在应该不返回.0.现在应该输出1k而不是1.0k.我只是检查了双倍和它的地板是否相同.

我在这个问题中找到了双扩展: 在swift中将double值舍入为x个小数位数

  • @Rajesh 而不是 round(self * divisor) / divisor,在 Swift 4 中做 (self * divisor).rounded() / divisor (2认同)

Ann*_*awn 12

以下扩展如下 -

  1. 将数字10456显示为10.5k,将10006显示为10k(不显示.0小数).
  2. 将对数百万的确切做以上并格式化,即10.5M和10M
  3. 将以货币格式格式化数千到9999,即使用逗号9,999

    extension Double {
        var kmFormatted: String {
    
            if self >= 10000, self <= 999999 {
                return String(format: "%.1fK", locale: Locale.current,self/1000).replacingOccurrences(of: ".0", with: "")
            }
    
            if self > 999999 {
                return String(format: "%.1fM", locale: Locale.current,self/1000000).replacingOccurrences(of: ".0", with: "")
            }
    
            return String(format: "%.0f", locale: Locale.current,self)
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

用法:

let num: Double = 1000001.00 //this should be a Double since the extension is on Double
let millionStr = num.kmFormatted
print(millionStr)
Run Code Online (Sandbox Code Playgroud)

打印 1M

在这里,它正在行动 -

在此输入图像描述


mit*_*a13 10

extension Int {
    var roundedWithAbbreviations: String {
        let number = Double(self)
        let thousand = number / 1000
        let million = number / 1000000
        if million >= 1.0 {
            return "\(round(million*10)/10)M"
        }
        else if thousand >= 1.0 {
            return "\(round(thousand*10)/10)K"
        }
        else {
            return "\(self)"
        }
    }
}

print(11.roundedWithAbbreviations)          // "11"
print(11111.roundedWithAbbreviations)       // "11.1K"
print(11111111.roundedWithAbbreviations)    // "11.1 M"
Run Code Online (Sandbox Code Playgroud)


Sté*_*pin 7

为了补充答案,这里有一个 Swift 4.X 版本,它使用循环在必要时轻松添加/删除单位:

extension Double {
    var shortStringRepresentation: String {
        if self.isNaN {
            return "NaN"
        }
        if self.isInfinite {
            return "\(self < 0.0 ? "-" : "+")Infinity"
        }
        let units = ["", "k", "M"]
        var interval = self
        var i = 0
        while i < units.count - 1 {
            if abs(interval) < 1000.0 {
                break
            }
            i += 1
            interval /= 1000.0
        }
        // + 2 to have one digit after the comma, + 1 to not have any.
        // Remove the * and the number of digits argument to display all the digits after the comma.
        return "\(String(format: "%0.*g", Int(log10(abs(interval))) + 2, interval))\(units[i])"
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

$ [1.5, 15, 1000, 1470, 1000000, 1530000, 1791200000].map { $0.shortStringRepresentation }
[String] = 7 values {
  [0] = "1.5"
  [1] = "15"
  [2] = "1k"
  [3] = "1.5k"
  [4] = "1M"
  [5] = "1.5M"
  [6] = "1791.2M"
}
Run Code Online (Sandbox Code Playgroud)


Aru*_*rma 5

答案有一些变化(对于整数,正确为百万):

func formatPoints(num: Int) ->String{
    let thousandNum = num/1000
    let millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(thousandNum == thousandNum){
            return("\(thousandNum)k")
        }
        return("\(thousandNum)k")
    }
    if num > 1000000{
        if(millionNum == millionNum){
            return("\(millionNum)M")
        }
        return ("\(millionNum)M")
    }
    else{
        if(num == num){
            return ("\(num)")
        }
        return ("\(num)")
    }

}
Run Code Online (Sandbox Code Playgroud)


Him*_*iya 5

对于斯威夫特4.0。它的工作完全正常,答案基于@user3483203

将 Double 值转换为 String 的函数

func formatPoints(num: Double) ->String{
    var thousandNum = num/1000
    var millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(floor(thousandNum) == thousandNum){
            return("\(Int(thousandNum))k")
        }
        return("\(thousandNum.roundToPlaces(places: 1))k")
    }
    if num > 1000000{
        if(floor(millionNum) == millionNum){
            return("\(Int(thousandNum))k")
        }
        return ("\(millionNum.roundToPlaces(places: 1))M")
    }
    else{
        if(floor(num) == num){
            return ("\(Int(num))")
        }
        return ("\(num)")
    }

}
Run Code Online (Sandbox Code Playgroud)

制作一个双扩展

extension Double {
    /// Rounds the double to decimal places value
    mutating func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }
}
Run Code Online (Sandbox Code Playgroud)

上述函数的使用

UILABEL.text = formatPoints(num: Double(310940)!)

输出 :

在此输入图像描述


小智 5

这是我的方法。

extension Int {
func shorted() -> String {
    if self >= 1000 && self < 10000 {
        return String(format: "%.1fk", Double(self/100)/10).replacingOccurrences(of: ".0", with: "")
    }
    
    if self >= 10000 && self < 1000000 {
        return "\(self/1000)k"
    }
    
    if self >= 1000000 && self < 10000000 {
        return String(format: "%.1fM", Double(self/100000)/10).replacingOccurrences(of: ".0", with: "")
    }
    
    if self >= 10000000 {
        return "\(self/1000000)M"
    }
    
    return String(self)
}
Run Code Online (Sandbox Code Playgroud)

以下是一些示例:

print(913.shorted())
print(1001.shorted())
print(1699.shorted())
print(8900.shorted())
print(10500.shorted())
print(17500.shorted())
print(863500.shorted())
print(1200000.shorted())
print(3010000.shorted())
print(11800000.shorted())

913
1k
1.6k
8.9k
10k
17k
863k
1.2M
3M
11M
Run Code Online (Sandbox Code Playgroud)