iosswiftnsdecimalnumber

NSDecimalNumber issues


In my iOS swift application, I receive some json from the web which contains some double values which represent currency. It looks like this:

[{"Amount": 5.0},{"Amount":-26.07},{"Amount": 4}, ...etc]

I cast these as Doubles and then try to feed these values as a Swift "Double" into the NSDecimalNumber's constructor like this:

let amount = NSDecimalNumber(double: amountAsDouble)

I'm running into problems with this approach because very frequently the NSDecimalNumber I created will contain a different number that goes 16 places passed the decimal point.

let amount = NSDecimalNumber(double: -15.97)
println(amount)

this returns -15.970000000000004096

I don't want this, I want -15.97. Thanks,


Solution

  • A Double is stored with 18 decimal digits, you can't do anything about that, it's how it works.

    Read here: http://en.wikipedia.org/wiki/Double-precision_floating-point_format

    However, at the time of displaying the value on the screen, you can use NSNumberFormatter like this:

    let amountInDouble: Double = -15.970000000000004096
    
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .DecimalStyle
    formatter.roundingIncrement = 0.01
    formatter.maximumFractionDigits = 2
    
    let amountAsString = formatter.stringFromNumber(NSNumber(double: amountInDouble))
    
    if let amountAsString = amountAsString {
        println(amountAsString) // -15.97
    }