Skip to content

Instantly share code, notes, and snippets.

@greenygh0st
Created July 7, 2022 17:43
Show Gist options
  • Save greenygh0st/b576b8433e24ef823bbe8d97edd71182 to your computer and use it in GitHub Desktop.
Save greenygh0st/b576b8433e24ef823bbe8d97edd71182 to your computer and use it in GitHub Desktop.
Formats numbers into a short hand format for easier reading.
extension Double {
func reduceScale(to places: Int) -> Double {
let multiplier = pow(10, Double(places))
let newDecimal = multiplier * self // move the decimal right
let truncated = Double(Int(newDecimal)) // drop the fraction
let originalDecimal = truncated / multiplier // move the decimal back
return originalDecimal
}
}
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.reduceScale(to: 1)
return "\(sign)\(formatted)B"
case 1_000_000...:
var formatted = num / 1_000_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)M"
case 1_000...:
var formatted = num / 1_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)K"
case 0...:
return "\(n)"
default:
return "\(sign)\(n)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment