如何从NSNumberFormatter获取确切的值?

时间:2015-08-18 23:54:27

标签: ios swift nsnumberformatter

从下面的代码中,我希望convertedN99999999,而是获得99999998。问题是在设置n之前存在舍入错误。我能做些什么才能得到我想要的结果?

let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let decimalAmount = NSDecimalNumber(decimal: n!.decimalValue)
let convertedN = (decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(unsignedLongLong: 100000000))).unsignedLongLongValue

2 个答案:

答案 0 :(得分:2)

请改用doubleValue。 NSDecimalNumber正在对数字进行四舍五入。

let amount = ".99999999"
let tmpFormatter = NSNumberFormatter()
tmpFormatter.maximumFractionDigits = 8
let n = tmpFormatter.numberFromString(amount)
let doubleValue = n!.doubleValue
let convertedN = doubleValue * 100000000

答案 1 :(得分:1)

试试这样:

let amount = ".99999999"
let decimalAmount = NSDecimalNumber(string: amount)
let convertedN = decimalAmount.decimalNumberByMultiplyingBy(NSDecimalNumber(string: "100000000")).unsignedLongLongValue   // 99,999,999