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

后端 未结 13 2191
陌清茗
陌清茗 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条回答
  •  失恋的感觉
    2021-01-01 13:25

    The extension below does the following-

    1. Will display number 10456 as 10.5k and 10006 as 10k (will not show the .0 decimals).
    2. Will do the exact above for millions and format it i.e. 10.5M and 10M
    3. Will format thousands upto 9999 in currency format i.e. with a comma like 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)
          }
      }
      

    Usage:

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

    Prints 1M

    And here it is in action-

提交回复
热议问题