快速将Double转换为科学计数法 [英] Convert Double to Scientific Notation in swift

查看:394
本文介绍了快速将Double转换为科学计数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将给定的double转换为科学计数法,并遇到一些问题.我似乎也找不到有关如何执行操作的大量文档.目前我正在使用:

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)

我在做什么错了?

推荐答案

您可以设置NumberFormatter属性positiveFormat和指数Symbol来设置字符串的格式,如下所示:

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"
}


更新: 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"

这篇关于快速将Double转换为科学计数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆