我有以下代码:
rangeSlider.minLabel?.text = "\(rangeSlider.lowerValue)"
标签文字 1e + 07 ,但我想成为100000000。
我应该如何禁用科学记数法?
答案 0 :(得分:9)
格式化您的数字样式:
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let finalNumber = numberFormatter.numberFromString("\(rangeSlider.lowerValue)")
print(finalNumber!)
转换简单的1e + 07
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let finalNumber = numberFormatter.numberFromString("\(1e+07)")
print(finalNumber!)
输出:
千万
希望这有帮助。
答案 1 :(得分:4)
另一种方法是使用导入String(format:)
时可用的Foundation
:
示例:
import Foundation // this comes with import UIKit or import Cocoa
let f: Float = 1e+07
let str = String(format: "%.0f", f)
print(str) // 10000000
在你的情况下:
rangeSlider.minLabel?.text = String(format: "%.0f", rangeSlider.lowerValue)
答案 2 :(得分:2)
我遇到了同样的问题。为了在字符串中显示这种数字,我创建了以下扩展名:
extension Double {
func toString(decimal: Int = 9) -> String {
let value = decimal < 0 ? 0 : decimal
var string = String(format: "%.\(value)f", self)
while string.last == "0" || string.last == "." {
if string.last == "." { string = String(string.dropLast()); break}
string = String(string.dropLast())
}
return string
}
}
用法示例:
var scientificNumber: Double = 1e+06
print(scientificNumber.toString()) // 1000000
scientificNumber = 1e-06
print(scientificNumber.toString()) // 0.000001
scientificNumber = 1e-14
print(scientificNumber.toString()) // 0 (too small for the default tollerance.)
print(scientificNumber.toString(decimal: 15)) // 0.00000000000001
对于浮点数也有效。只需扩展Float而不是Double。
答案 3 :(得分:2)
Swift 4.2
禁用科学计数法:
let number = NSNumber(value: rangeSlider.lowerValue)
print(number.decimalValue)
rangeSlider.minLabel?.text = "\(number.decimalValue)"