Home > Enterprise >  Get x amount of initial digits in a long Number
Get x amount of initial digits in a long Number

Time:01-29

I have some numbers coming from the api like this: 0.0000000092726851369802

How can I get the index (which can change) of the last 0 before the 9 and from there count 4 and return those numbers? So it would look like: 0.000000009272 returning only the 4 last values after the 0s

Looking for a Swift 5 solution

CodePudding user response:

@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)

You can use formatted method and set the number precision significant digits to four:

let decimal = Decimal(string: "9.272685136e-9")!
decimal.formatted(.number.precision(.significantDigits(4)))  // "0.000000009273"

For older iOS versions you can create a custom Numeric formatter as follow:


extension Formatter {
    static let significantDigits: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.usesSignificantDigits = true
        return formatter
    }()
}

extension Numeric {
    func maximumSignificantDigits(_ digits: Int = 4) -> String {
        Formatter.significantDigits.maximumSignificantDigits = digits
        return Formatter.significantDigits.string(for: self) ?? ""
    }
}

let decimal = Decimal(string: "9.272685136e-9")!
decimal.maximumSignificantDigits()  // "0.000000009273"
  •  Tags:  
  • Related