Swift 4:将数字格式化为友好的K.

时间:2018-01-21 19:57:57

标签: swift

目前正致力于一项对我来说很棒的简单功能..

例如: 如果我有1000,它将打印1.0K,或1,000,000它将是1M,一切正常,直到这里,

  

如果我想将1,000,000,000变成1B?

我尝试了以下内容 - >

func formatPoints(from: Int) -> String {
     let number = Double(from)
     let thousand = number / 1000
     let million = number / 1000000
     let billion = number / 1000000000

     if million >= 1.0 { 
     return "\(round(million*10)/10)M" 
} else if thousand >= 1.0 { 
     return "\(round(thousand*10)/10)K"
} else if billion >= 1.0 {
        return ("\(round(billion*10/10))B")
} else {
    return "\(Int(number))"}
}

print(formatPoints(from: 1000000000))

但它返回1000.0M,而不是1B

谢谢!

2 个答案:

答案 0 :(得分:8)

我个人不喜欢在格式化这样的数字时舍入,我更喜欢截断。在接受的答案中,1,515向上舍入,以便在您可能获得2k时向您1.5k。因此,如果您希望截断舍入,请考虑此方法:

extension Double {
    func truncate(places: Int) -> Double {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

func formatNumber(_ n: Int) -> String {

    let num = abs(Double(n))
    let sign = (n < 0) ? "-" : ""

    switch num {

    case 1_000_000_000...:
        var formatted = num / 1_000_000_000
        formatted = formatted.truncate(places: 1)
        return "\(sign)\(formatted)B"

    case 1_000_000...:
        var formatted = num / 1_000_000
        formatted = formatted.truncate(places: 1)
        return "\(sign)\(formatted)M"

    case 1_000...:
        var formatted = num / 1_000
        formatted = formatted.truncate(places: 1)
        return "\(sign)\(formatted)K"

    case 0...:
        return "\(n)"

    default:
        return "\(sign)\(n)"

    }

}

对于您希望进一步截断的特定情况,您可以非常轻松地微调此方法,例如100k而不是100.5k1M而不是1.1M。此方法也处理否定。

print(formatNumber(1515)) // 1.5K
print(formatNumber(999999)) // 999.9K
print(formatNumber(1000999)) // 1.0M

答案 1 :(得分:3)

i0 = 0; for(p1=0;p1<=6;p1++) { for(p2=7;p2<=13;p2++) { for(p3=14;p3<=20;p3++) { for(p4=21;p4<=27;p4++) { for(p5=28;p5<=34;p5++) { for(p6=35;p6<=41;p6++) { for(p7=42;p7<=48;p7++) { for(p8=49;p8<=55;p8++) { for(p9=56;p9<=62;p9++) { for(p10=63;p10<=69;p10++) { comb[i0 * 10 + 0] = p1; comb[i0 * 10 + 1] = p2; comb[i0 * 10 + 2] = p3; comb[i0 * 10 + 3] = p4; comb[i0 * 10 + 4] = p5; comb[i0 * 10 + 5] = p6; comb[i0 * 10 + 6] = p7; comb[i0 * 10 + 7] = p8; comb[i0 * 10 + 8] = p9; comb[i0 * 10 + 9] = p10; i0++; } } } } } } } } } } 语句的以下逻辑向您展示了第一个和最后一个:

if-else

亿万必须先行。