2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Intに数字の単位をつけて表示させたい (Ex. 1,000 -> 1K, 2,000,000 -> 2M)

Posted at

Development Environment

  • OS X El Captain 10.11.2
  • Xcode Version 8.0

#Language
Swift 3.0

#Step
1 Create Int Extension file

Int+Extension.swift
import UIKit

extension Int {
    // 数値省略処理
    func AbbreviationFormatter () -> String {
        let numberFormatter = NumberFormatter()
        typealias Abbreviation = (threshold:Double, divisor:Double, suffix:String)
        // 単位のパターン宣言はここで. Add more abbreviation from here
        let abbreviationsUnits:[Abbreviation] = [(0, 1, ""),(100.0, 1000.0, "K"),(100_000.0, 1_000_000.0, "M"), (100_000_000.0, 1_000_000_000.0, "B")]
 
        let initialValue = Double (abs(self))
        let abbreviation:Abbreviation = {
            var after = abbreviationsUnits[0]
            for temp in abbreviationsUnits {
                if (initialValue < temp.threshold) {
                    break
                }
                after = temp
            }
            return after
        } ()
        let actualValue = Double(self) / abbreviation.divisor
        numberFormatter.positiveSuffix = abbreviation.suffix
        numberFormatter.negativeSuffix = abbreviation.suffix
        numberFormatter.allowsFloats = true
        numberFormatter.minimumIntegerDigits = 1
        numberFormatter.minimumFractionDigits = 0
        numberFormatter.maximumFractionDigits = 1
        return numberFormatter.string(from: NSNumber (value:actualValue))!
    }
}

2 You can use that extension with int parameter

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let number1 = 5000
        let number2 = 500000
        let number3 = 5000000
        let number4 = 5000000000
        
        print (number1.AbbreviationFormatter())
        print (number2.AbbreviationFormatter())
        print (number3.AbbreviationFormatter())
        print (number4.AbbreviationFormatter())

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

3 Output will be following:
5K 0.5M 5M 5B

4 Done

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?