Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

ios - How to display 12,4K with var NumberFollowers = 12458 in swift?

How to display 12,4K with the variable NumberFollowers = 12458 in swift ?

The number displayed (12,4K) should change value as soon as NumberFollower changes value.

Example: if NumberFollowers is equal to 45875, the number displayed must be equal to 45,8K

PS: I have a problem with the 12,4K comma.

This is what i want to display :

1234 -> 1 234

12345 -> 12,3K

123456 -> 123K

1234567 -> 1,2M

12345678 -> 12,3M

123456789 -> 123M

Here is what I have

if NumberFollowers > 999999 {
    NumberFollowersLabel.text = "(NumberFollowers/1000000) M"
} else if NumberFollowers > 9999 {
    NumberFollowersLabel.text = "(NumberFollowers/1000) K"
} else {
    NumberFollowersLabel.text = "(NumberFollowers)"
}

This is what my code displays

1234 -> 1 234

12345 -> 12K

123456 -> 123K

1234567 -> 1M

12345678 -> 12M

123456789 -> 123M


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is one way - based on the way you have shown how you want the values formatted:

func formatNumber(_ i: Int) -> String {
    let nf = NumberFormatter()
    nf.usesGroupingSeparator = true
    nf.numberStyle = .decimal
    
    var newNum: Double = 0
    var numDec: Int = 0
    var sPost: String = ""
    
    switch i {
    case 0..<10_000:
        newNum = Double(i)
    case 10_000..<100_000:
        newNum = Double(i) / 1_000.0
        numDec = 1
        sPost = "K"
    case 100_000..<1_000_000:
        newNum = Double(i) / 1_000.0
        sPost = "K"
    case 1_000_000..<100_000_000:
        newNum = Double(i) / 1_000_000.0
        numDec = 1
        sPost = "M"
    default:
        newNum = Double(i) / 1_000_000.0
        sPost = "M"
    }

    nf.maximumFractionDigits = numDec
    return (nf.string(for: newNum) ?? "0") + sPost
}

To check:

    let a: [Int] = [
        1234,
        12345,
        123456,
        1234567,
        12345678,
        123456789
    ]
    
    a.forEach { n in
        print(formatNumber(n))
    }

The Thousand and Decimal separators will be based on the default for the locale.

So, the debug output from that with a USA locale is:

1,234
12.3K
123K
1.2M
12.3M
123M

and, for example, with a Germany locale:

1.234
12,3K
123K
1,2M
12,3M
123M

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...