Search code examples
iosswiftmathnsnumberformatter

Convert Double to Scientific Notation in swift


I am trying to convert a given double into scientific notation, and running into some problems. I cant seem to find much documentation on how to do it either. Currently I am using:

 var val = 500
 var numberFormatter = NSNumberFormatter()
 numberFormatter.numberStyle = NSNumberFormatterStyle.ScientificStyle
 let number = numberFormatter.numberFromString("\(val)")
 println(number as Double?) 
 // Prints optional(500) instead of optional(5e+2)

What am I doing wrong?


Solution

  • You can set NumberFormatter properties positiveFormat and exponent Symbol to format your string as you want as follow:

    let val = 500
    let formatter = NumberFormatter()
    formatter.numberStyle = .scientific
    formatter.positiveFormat = "0.###E+0"
    formatter.exponentSymbol = "e"
    if let scientificFormatted = formatter.string(for: val) {
        print(scientificFormatted)  // "5e+2"
    }
    

    update: Xcode 9 • Swift 4

    You can also create an extension to get a scientific formatted description from Numeric types as follow:

    extension Formatter {
        static let scientific: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.numberStyle = .scientific
            formatter.positiveFormat = "0.###E+0"
            formatter.exponentSymbol = "e"
            return formatter
        }()
    }
    

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

    print(500.scientificFormatted)   // "5e+2"