Swift 2.0 Format 1000's into a friendly K's

后端 未结 13 2198
陌清茗
陌清茗 2021-01-01 12:51

I\'m trying to write a function to present thousands and millions into K\'s and M\'s For instance:

1000 = 1k
1100 = 1.1k
15000 = 15k
115000 = 115k
1000000 =          


        
13条回答
  •  梦毁少年i
    2021-01-01 13:31

    I have converted @AnBisw's answer to use switch (build time friendly):

       extension Double {
        var kmFormatted: String {
            switch self {
            case ..<1_000:
                return String(format: "%.0f", locale: Locale.current, self)
            case 1_000 ..< 999_999:
                return String(format: "%.1fK", locale: Locale.current, self / 1_000).replacingOccurrences(of: ".0", with: "")
            default:
                return String(format: "%.1fM", locale: Locale.current, self / 1_000_000).replacingOccurrences(of: ".0", with: "")
            }
        }
    }
    

提交回复
热议问题