Swift 2.0 将 1000 格式化为友好的 K

Swift 2.0 Format 1000#39;s into a friendly K#39;s(Swift 2.0 将 1000 格式化为友好的 K)
本文介绍了Swift 2.0 将 1000 格式化为友好的 K的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数来将成千上万的数字呈现为 K 和 M例如:

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 = 1m

这是我到目前为止的地方:

Here is where I got so far:

func formatPoints(num: Int) -> String {
    let newNum = String(num / 1000)
    var newNumString = "(num)"
    if num > 1000 && num < 1000000 {
        newNumString = "(newNum)k"
    } else if num > 1000000 {
        newNumString = "(newNum)m"
    }

    return newNumString
}

formatPoints(51100) // THIS RETURNS 51K instead of 51.1K

如何让这个功能工作,我错过了什么?

How do I get this function to work, what am I missing?

推荐答案

func formatPoints(num: Double) ->String{
    let thousandNum = num/1000
    let millionNum = num/1000000
    if num >= 1000 && num < 1000000{
        if(floor(thousandNum) == thousandNum){
            return("(Int(thousandNum))k")
        }
        return("(thousandNum.roundToPlaces(1))k")
    }
    if num > 1000000{
        if(floor(millionNum) == millionNum){
            return("(Int(thousandNum))k")
        }
        return ("(millionNum.roundToPlaces(1))M")
    }
    else{
        if(floor(num) == num){
            return ("(Int(num))")
        }
        return ("(num)")
    }

}

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}

如果数字是整数,更新后的代码现在不应返回 .0.例如,现在应该输出 1k 而不是 1.0k.我只是检查了 double 和它的 floor 是否相同.

The updated code should now not return a .0 if the number is whole. Should now output 1k instead of 1.0k for example. I just checked essentially if double and its floor were the same.

我在这个问题中找到了双重扩展名:将一个双精度值舍入到 x 个swift中的小数位

I found the double extension in this question: Rounding a double value to x number of decimal places in swift

这篇关于Swift 2.0 将 1000 格式化为友好的 K的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)