danthorpe / Money

Swift value types for working with money & currency
MIT License
933 stars 91 forks source link

How to get Double value as the same Money value? #72

Closed alexanderkhitev closed 7 years ago

alexanderkhitev commented 7 years ago

Hello! I was faced with incorrect converting to Double. For example I have a value of SGD 99.68, when I take a Double value, it turns out I 98.679999999999993 so, how do I get the value of a level 99.68 as a Double?

danthorpe commented 7 years ago

Hi @alexsanderkhitev, how were you converting to a Double? Did you do this?

let money: SGD = 99.68
let double = money.amount.doubleValue

This is because the number is represented in a StorageType which for SGD is NSDecimalNumber, and this is accessed via the amount property. NSDecimalNumber has an API to get the number represented as a Double.

Note also, that if your value of 99.68 was not a literal, but the result of a calculation, then it very well might actually be 98.6799999999999993, but SGD represents this numeric value as expected with the correct fractional digits and rounding. This is why it is essential to perform monetary arithmetic using NSDecimalNumber, Decimal or as strict integers.

alexanderkhitev commented 7 years ago

@danthorpe thanks!