Scale and Precision of NSDecimalNumber value

603 Views Asked by At

Let us suppose I have a variable v of type NSDecimalNumber

let v = 34.596904 in its own format.

I want to know the precision and scale of this number, not the default one. I did not find any function in the NSDecimalNumber class which gives these values or maybe someone would like to throw some light on how it works.

precision = 8
scale = 6

precision is count of significant digits in number and scale is count of significant digit after decimal

1

There are 1 best solutions below

0
OOPer On

This extension will give you the specific value for your only example:

extension Decimal {
    var scale: Int {
        return -self.exponent
    }

    var precision: Int {
        return Int(floor(log10((self.significand as NSDecimalNumber).doubleValue)))+1
    }
}

Usage:

let v: NSDecimalNumber = NSDecimalNumber(string: "34.596904")

print("precision=\((v as Decimal).precision)") //->precision=8
print("scale=\((v as Decimal).scale)") //->scale=6

But I cannot be sure if this generates expected results in all cases you have in mind, as you have shown only one example...


One more, in Swift, Decimal and NSDecimalNumber are easily bridgeable and you should better use Decimal as far as you can.