本文介紹了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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!