Search code examples
swiftnsdecimalnumber

Java BigDecimal in Swift


What data type I can use for parsing Java BigDecimal? In Objective - C it can be done by using NSDecimalNumber. Do I have Swift-native solution (without using NSDecimalNumber)?


Solution

  • This may not be what you want, as you are saying swift-native solution. But in Swift 3, an old C-struct based NSDecimal is imported as Decimal, and a big re-arrangement for it has been done as to say "it is nearly Swift-native".

    let deca = 1.23 as Decimal //<- This actually may produce some conversion error, while `ExpressibleByFloatLiteral` uses `Double` as an intermediate value.
    let decb = 0.01 as Decimal
    print(deca + decb == 1.24) //->true
    

    UPDATE Added a simple example, where you can find a calculation error in Double (binary floating point system). (Tested in Xcode 8 beta 6.)

    let dblc = 0.000001
    let dbld = 100 as Double
    let dble = 0.0001
    print(dblc * dbld == dble) //->false (as Double cannot represent decimal fractions precisely)
    
    let decc = Decimal(string: "0.000001")! //<- avoiding conversion error
    let decd = 100 as Decimal //<- integer literal may not generate conversion error
    let dece = Decimal(string: "0.0001")!
    print(decc * decd == dece) //->true