Reputation: 2680
I have the following code :
rangeSlider.minLabel?.text = "\(rangeSlider.lowerValue)"
The label text is 1e+07 but I want to be 100000000.
How should I disable scientific notation ?
Upvotes: 13
Views: 10671
Reputation: 23882
Format your number style :
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
let finalNumber = numberFormatter.number(from: "\(rangeSlider.lowerValue)")
print(finalNumber!)
With the conversion of simple 1e+07
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
let finalNumber = numberFormatter.number(from: "\(1e+07)")
print(finalNumber!)
Output :
10000000
Hope this helps.
Upvotes: 14
Reputation: 529
Swift 4.2
Disable scientific notation:
let number = NSNumber(value: rangeSlider.lowerValue)
print(number.decimalValue)
rangeSlider.minLabel?.text = "\(number.decimalValue)"
Upvotes: 5
Reputation: 1660
I've just had the same problem to face. For displaying this kind of numbers in a string, I've created the following extension:
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
}
}
Usage example:
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
For floats works as well. Just extend Float instead of Double.
Upvotes: 6
Reputation: 154651
Another approach is to use String(format:)
which is available if you have Foundation
imported:
Example:
import Foundation // this comes with import UIKit or import Cocoa
let f: Float = 1e+07
let str = String(format: "%.0f", f)
print(str) // 10000000
In your case:
rangeSlider.minLabel?.text = String(format: "%.0f", rangeSlider.lowerValue)
Upvotes: 8