Convert Double to Scientific Notation in swift

好久不见. 提交于 2021-02-16 07:50:27

问题


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?


回答1:


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"



回答2:


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)



回答3:


Slight modification to the answer by leo-dabus to Xcode 9 Swift 4:

extension Double {
    struct Number {
        static var formatter = NumberFormatter()
    }
    var scientificStyle: String {
        Number.formatter.numberStyle = .scientific
        Number.formatter.positiveFormat = "0.###E+0"
        Number.formatter.exponentSymbol = "e"
        let number = NSNumber(value: self)
        return Number.formatter.string(from :number) ?? description
    }
}


来源:https://stackoverflow.com/questions/31934088/convert-double-to-scientific-notation-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!