3 swift
目前正在开发一个简单的功能,对我来说做得很好..
例如:如果我有1000,它将打印1.0K,或1,000,000它将是1M,一切正常,直到这里,
如果我想将1,000,000,000转为1B怎么办?
我尝试了以下 - >
func formatPoints(from: Int) -> String {
let number = Double(from)
let thousand = number / 1000
let million = number / 1000000
let billion = number / 1000000000
if million >= 1.0 {
return "\(round(million*10)/10)M"
} else if thousand >= 1.0 {
return "\(round(thousand*10)/10)K"
} else if billion >= 1.0 {
return ("\(round(billion*10/10))B")
} else {
return "\(Int(number))"}
}
print(formatPoints(from: 1000000000))
Run Code Online (Sandbox Code Playgroud)
但它返回1000.0M,而不是1B
谢谢!
我个人不喜欢在格式化这样的数字时舍入,我更喜欢截断.在接受的答案中,1,515四舍五入是为了给你2k什么时候应该得到的1.5k.因此,如果您希望截断舍入,请考虑此方法:
extension Double {
func truncate(places: Int) -> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
func formatNumber(_ n: Int) -> String {
let num = abs(Double(n))
let sign = (n < 0) ? "-" : ""
switch num {
case 1_000_000_000...:
var formatted = num / 1_000_000_000
formatted = formatted.truncate(places: 1)
return "\(sign)\(formatted)B"
case 1_000_000...:
var formatted = num / 1_000_000
formatted = formatted.truncate(places: 1)
return "\(sign)\(formatted)M"
case 1_000...:
var formatted = num / 1_000
formatted = formatted.truncate(places: 1)
return "\(sign)\(formatted)K"
case 0...:
return "\(n)"
default:
return "\(sign)\(n)"
}
}
Run Code Online (Sandbox Code Playgroud)
对于需要进一步截断的特定情况,您可以非常轻松地微调此方法,例如100k代替100.5k或1M替代1.1M.此方法也处理否定.
print(formatNumber(1515)) // 1.5K
print(formatNumber(999999)) // 999.9K
print(formatNumber(1000999)) // 1.0M
Run Code Online (Sandbox Code Playgroud)
以下if-else语句逻辑向您展示了什么是先发生的,什么是最后发生的:
import Foundation
func formatPoints(from: Int) -> String {
let number = Double(from)
let thousand = number / 1000
let million = number / 1000000
let billion = number / 1000000000
if billion >= 1.0 {
return "\(round(billion*10)/10)B"
} else if million >= 1.0 {
return "\(round(million*10)/10)M"
} else if thousand >= 1.0 {
return ("\(round(thousand*10/10))K")
} else {
return "\(Int(number))"
}
}
print(formatPoints(from: 1000)) /* 1.0 K */
print(formatPoints(from: 1000000)) /* 1.0 M */
print(formatPoints(from: 1000000000)) /* 1.0 B */
Run Code Online (Sandbox Code Playgroud)
亿必须先走。