Java BigDecimal in Swift

What data type can I use to parse Java BigDecimal ? In Objective-C, this can be done using NSDecimalNumber . Do I have a Swift-native solution (without using NSDecimalNumber )?

+7
swift nsdecimalnumber
source share
1 answer

This may not be what you want, as you say a quick fix. But in Swift 3, the old NSDecimal based C-struct is imported as Decimal , and a big overhaul for it was made to say: "it's almost 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 A simple example has been added where you can find the 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 
+7
source share

All Articles