Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
modesitt Avatar asked Aug 11 '15 05:08

modesitt


2 Answers

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"
like image 127
Leo Dabus Avatar answered Nov 13 '22 06:11

Leo Dabus


The issue is that you are printing the number... not the formatted number. You are calling numberForString instead of stringForNumber

var val = 500
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.ScientificStyle
let numberString = numberFormatter.stringFromNumber(val)
println(numberString)
like image 37
Good Doug Avatar answered Nov 13 '22 05:11

Good Doug