Home > Software design >  Convert string number with exponent to double value in swift
Convert string number with exponent to double value in swift

Time:10-06

How would I convert a string value with a exponent to a double value that I can use in a calculation

Example: var newString = "2.9747E 03"

I want to turn that string into a number I can use in formulas.

CodePudding user response:

This might help solve your problem:

https://developer.apple.com/forums/thread/31383

CodePudding user response:

Use a NumberFormatter object.

Those objects have a method number(from:) that let you convert a String to an NSNumber. The existing style .scientific might meet your needs, or you might need to create a custom format string.

This code works:

var numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .scientific
if let value = numberFormatter.number(from:"2.9747E 03")
{
    let dVal = Double(truncating: value)
    print(dVal)
}

And outputs

2974.7

  • Related