Based on the solution from @qlear.
I've noticed that if the number was exactly 1000000, it would return 1000000 unformatted.
So I've added that into the function. I also included negative values.. since not everyone is always making a profit!
func formatPoints(num: Double) ->String{
let thousandNum = num/1000
let millionNum = num/1000000
if num > 0
{
if num >= 1000 && num < 1000000{
if(floor(thousandNum) == thousandNum){
return("\(Int(thousandNum))k")
}
return("\(round1(thousandNum, toNearest: 0.01))k")
}
if num > 1000000{
if(floor(millionNum) == millionNum){
return("\(Int(thousandNum))k")
}
return ("\(round1(millionNum, toNearest: 0.01))M")
}
else if num == 1000000
{
return ("\(round1(millionNum, toNearest: 0.01))M")
}
else{
if(floor(num) == num){
return ("\(Int(num))")
}
return ("\(round1(num, toNearest: 0.01))")
}
}
else
{
if num <= -1000 && num > -1000000{
if(floor(thousandNum) == thousandNum){
return("\(Int(thousandNum))k")
}
return("\(round1(thousandNum, toNearest: 0.01))k")
}
if num < -1000000{
if(floor(millionNum) == millionNum){
return("\(Int(thousandNum))k")
}
return ("\(round1(millionNum, toNearest: 0.01))M")
}
else if num == -1000000
{
return ("\(round1(millionNum, toNearest: 0.01))M")
}
else{
if(floor(num) == num){
return ("\(Int(num))")
}
return ("\(round1(num, toNearest: 0.01))")
}
}
}
And the number extension of course:
extension Double {
/// Rounds the double to decimal places value
func round1(_ value: Double, toNearest: Double) -> Double {
return Darwin.round(value / toNearest) * toNearest
}
}
NSByteCountFormatter
instead of your own code. – PontusInt
value as input, sonum / 1000
is probably not returning any decimals. – Sandglass1000.formatted(.number.notation(.compactName))
(See developer.apple.com/documentation/foundation/…). – Finisterre