本文介绍了Swift的小数精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档此处,Swift 3/4十进制类型是一种表示形式在以10为基数桥接到NSDecimalNumber.但是,我遇到了使用NSDecimalNumber时无法重现的精度问题.

According to the docs here, Swift 3/4 Decimal type is a representation in base 10 bridged to NSDecimalNumber. However I'm having precision issues that do not reproduce when using NSDecimalNumber.

let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24
// prints 0.99999999999999999999999999999999999984

let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)
// prints 1

小数"结构不准确,还是我误会了什么?

Shouldn't the Decimal struct be accurate, or am I misunderstanding something?

推荐答案

NSDecimalNumber(及其覆盖类型Decimal)可以代表

因此,十进制分数(最多38个十进制数字)可以表示准确,但不是任意数字.特别是1/24 = 0.416666666...具有无限多个小数位数(重复小数),并且不能为完全表示为Decimal.

So decimal fractions (with up to 38 decimal digits) can be representedexactly, but not arbitrary numbers. In particular 1/24 = 0.416666666...has infinitely many decimal digits (a repeating decimal) and cannot berepresented exactly as a Decimal.

DecimalNSDecimalNumber之间也没有精度差异.如果我们打印出差异,这将变得显而易见在实际结果和理论结果"之间:

Also there is no precision difference between Decimal and NSDecimalNumber. That becomes apparent if we print the differencebetween the actual result and the "theoretical result":

let dec24 = Decimal(integerLiteral: 24)
let dec1 = Decimal(integerLiteral: 1)
let decResult = dec1/dec24*dec24

print(decResult - dec1)
// -0.00000000000000000000000000000000000016


let dn24 = NSDecimalNumber(value: 24)
let dn1 = NSDecimalNumber(value: 1)
let dnResult = dn1.dividing(by: dn24).multiplying(by: dn24)

print(dnResult.subtracting(dn1))
// -0.00000000000000000000000000000000000016

这篇关于Swift的小数精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:27