ekeith
ekeith

Reputation: 644

How to know the unit of a number in swift?

I'm trying to detect the type of number a user enters into a textField. For example

if the user enters 1000 The program should return 1Kcs

if the user enters 12,000, The program should return 12Kcs

if the user enters 12,000,000 The program should return 12MCS

How do I go about this in swift?

Thousands - Kcs Hundreds - Mcs

Upvotes: 0

Views: 233

Answers (2)

MShahmeer
MShahmeer

Reputation: 159

Some variation of this to fit your needs should be fine:

var num = 12000000

switch num {
case 1000...999999:
    print(String(num/1000) + "Kcs")
case 1000000...999999999:
    print(String(num/1000000) + "Mcs")
default:
    print(num)
}

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59496

This should to the job

extension Int {
    var unitFormatted: String {
        let positive = self < 0 ? -self : self
        switch positive {
        case 1_000_000..<Int.max: return "\(self / 1_000_000)MCS"
        case 1_000..<1_000_000: return "\(self / 1_000)Kcs"
        default: return "\(self)"
        }
    }
}

Examples

0.unitFormatted // "0"
1.unitFormatted // "1"
1000.unitFormatted // "1Kcs"
12000.unitFormatted // "12Kcs"
12000000.unitFormatted // "12MCS"

Upvotes: 2

Related Questions