How To Create Decimal From Double

If you encounter a problem with double’s precision you might think about using Decimal.

However sometimes, you might find that when you use something like this:

let double: Double = 10.01
let decimal: Decimal = Decimal(double)
print(decimal)

You might get 10.0999999999999999997 instead of 10.01 you expected.

I found a way to remove this problem using String.

let double: Double = 10.01
let decimal: Decimal = Decimal(string: double.description) ?? Decimal(0)

Of course creating Decimal from the string might return nil but until you make it comes from Double variable you might be sure it won’t return nil.