Swift将大数字转换为小数字并附加' K'或者' M'

时间:2017-02-22 12:33:25

标签: ios swift swift3 nsnumberformatter

我想用NumberFormatter将一个大数字转换为一个小数字。

910 => 91
45893 => 45

但是我的程序对这个例子不起作用:

910394529348 => 0

我的代码对于小数字是正确的,但是当我的变量' powCalc'大于7位NumberFormatter返回0.实际上我认为乘数类型(NSNumber)和限制。这是对的吗?

import Foundation
import UIKit

let maximumSignificantDigits: Double = 2
var myValue = 910394529348
let len = ceil (log10 ( Double(myValue)))
var short = Int(len - maximumSignificantDigits)

short -= (short % 3)

var positiveFormat = ""

switch short {
case 0:
    positiveFormat = ""
case 3:
    positiveFormat = "K"
case 6:
    positiveFormat = "M"
default:
    positiveFormat = "etc"
}

let powCalc = 1.0 / pow(10, Double(short))

let numberFormatter = NumberFormatter()
numberFormatter.multiplier =  powCalc as NSNumber!
numberFormatter.maximumFractionDigits = 0

numberFormatter.positiveFormat = "0" + positiveFormat

stride(from: 0, to: myValue, by: myValue / 10).map {counter in
    print(counter, Double(counter) * powCalc, numberFormatter.string(from: NSNumber(value: counter))!)
}

返回' myValue' 0!

但是如果你将myValue更改为523478或其他程序,那么程序就可以正常工作。

0 个答案:

没有答案