简体   繁体   中英

Get x amount of initial digits in a long Number

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

What @matt suggested is to get the first four digits of your string and the exponent. Try this:

let string = "9.272685136e-9"
if let lowerBound = string.range(of: "e-")?.lowerBound,
    case let mantissa = string[..<lowerBound].prefix(5),
    case let exponent = string[lowerBound...],
    case let finalValue = [mantissa,exponent].joined(),
    let decimal = Decimal(string: finalValue) {
    print(decimal)
}

edit/update:

If your value comes without scientific notation you can simply use number formatter to convert it:

extension Formatter {
    static let scientific: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .scientific
        return formatter
    }()
}

extension Decimal {
    var scientific: String { Formatter.scientific.string(for: self) ?? "" }
}

let decimal = Decimal(string: "0.0000000092726851369802")!
let scientific = decimal.scientific  // "9.2726851369802E-9"
if let lowerBound = scientific.range(of: "e-", options: .caseInsensitive)?.lowerBound,
    case let mantissa = scientific[..<lowerBound].prefix(5),
    case let exponent = scientific[lowerBound...],
    case let finalValue = [mantissa,exponent].joined(),
    let decimal = Decimal(string: finalValue) {
    print(decimal)  // "0.000000009272\n"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM