How to store 1.66 in NSDecimalNumber

I know that float or double are not suitable for storing a decimal number, such as money and quantity. Instead, I'm trying to use NSDecimalNumber. Here is my code on the Swift playground.

let number:NSDecimalNumber = 1.66 let text:String = String(describing: number) NSLog(text) 

Console Output: 1.6599999999999995904

How can I store the exact decimal value of 1.66 in a variable?

+7
source share
1 answer

IN

 let number:NSDecimalNumber = 1.66 

the right side is a floating point number that cannot accurately represent the value of "1.66". One option is to create a decimal number from a string:

 let number = NSDecimalNumber(string: "1.66") print(number) // 1.66 

Another option is to use arithmetic:

 let number = NSDecimalNumber(value: 166).dividing(by: 100) print(number) // 1.66 

In Swift 3, you can use "overlay value type" instead of Decimal , for example

 let num = Decimal(166)/Decimal(100) print(num) // 1.66 

Another option:

 let num = Decimal(sign: .plus, exponent: -2, significand: 166) print(num) // 1.66 

Application:

Related Discussions in the Swift Forum:

Related error messages:

+10
source

Source: https://habr.com/ru/post/1265428/


All Articles