Search code examples
swiftnsdecimalnumber

Why subtracting NSDecimalNumbers do not work - Swift 3


Why am I getting 0 when subtracting 5.0 from 650.50 using the subtracting() method?

in the following code, adding, multiplying and dividing work fine, but why subtracting doesn't? What am I doing wrong?

See code in IBM's sandbox: http://swift.sandbox.bluemix.net/#/repl/59b1387696a0602d6cb19201

import Foundation

let num1:NSDecimalNumber = 650.50
let num2:NSDecimalNumber = 5.0 

let result = num1.adding(num2)
let result2 = num1.subtracting(num2)
let result3 = num1.multiplying(by: num2)
let result4 = num1.dividing(by: num2)

print("Addition: \(result)") // Addition: 655.5
// Why am I getting 0 here and not 645.5?
print("Subtraction: \(result2)") //Subtraction: 0
print("Multiplication: \(result3)") //Multiplication: 3252.5
print("Division: \(result4)") //Division: 130.1

Apples Docs: https://developer.apple.com/documentation/foundation/nsdecimalnumber


Solution

  • This may be because of a specificity of the IBM sandbox related to NSDecimalNumber (indeed many parts of Foundation are still not entirely available on Linux).

    Anyway, whatever the bug is, a solution is to use the Swift counterpart to NSDecimalNumber which is Decimal.

    Despite the fact that this is supposed to be only a wrapper around NSDecimalNumber, it gives the correct result, even on the IBM platform.

    Note that this wrapper doesn't use the NSDecimalNumber methods, it uses Swift operators such as + or *.

    import Foundation
    
    let num1: Decimal = 650.50
    let num2: Decimal = 5.0
    
    let result = num1 + num2
    let result2 = num1 - num2
    let result3 = num1 * num2
    let result4 = num1 / num2
    
    print("Addition: \(result)")
    print("Subtraction: \(result2)")
    print("Multiplication: \(result3)")
    print("Division: \(result4)")
    

    Gives:

    Addition: 655.5
    Subtraction: 645.5
    Multiplication: 3252.5
    Division: 130.1