I'm trying to convert a Decimal number which represents a dollar amount. Then I cast it into a NSDecimalNumber to apply .intValue transformation.
However I am getting weird behaviors. First it will give me an imprecise value when multiplying the value by 100. And when applying .intValue I get a completely unexpected number. Would appreciate your help!
//Issue
let dollars: Decimal = 106.99 * 100 // 10698.999999999997952
let cast = dollars as NSDecimalNumber // 10699
let int = cast.intValue //-7747
//No Problems here
let dollars2: Decimal = 106.98 * 100 // 10698
let cast2 = dollars2 as NSDecimalNumber // 10698
let int2 = cast2.intValue //10698
Decimal'sFloatLiteralTypeisDouble.Trouble is,
106.99can't be represented byDouble. Just popping it into aDecimalis problematic:So, you've got to sanitize your
Doubles.This is fine in practice because
Decimalis for money. Sanitize and you'll never run into bugs.