Swift - How to convert String to Double
Swift 4.2+ String to Double
You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.
Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).
let lessPrecisePI = Float("3.14")
let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number
Unwrap the values to use them using if/let
if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}
You can convert formatted numbers and currency using the NumberFormatter
class.
let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")
Currency formats
let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency
formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")
formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €
formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator
formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")
Read more on my blog post about converting String to Double types (and currency).
String Convert into double in swift 4.1
You like this to convert String
into Double
:
let getLongijson: String = "67.0011"
let getlatijson: String = "24.8607"
let jsonlong = Double(getLongijson)
let jsonlat = Double(getlatijson)
Unable to convert String to double Swift
Please try this:
extension String {
func toDouble() -> Double? {
return NumberFormatter().number(from: self)?.doubleValue
}
}
You can access like that:
var myString = "1.2"
var myDouble = myString.toDouble()
You can remove optional as below:
if let data:NSDictionary = snap.value as! NSDictionary, let lat = data.value(forKey: "lat"),let lng = data.value(forKey: "lng") {
//then use thes let long to convert in Double
let latValue = lat.toDouble()
let lngValue = lng.toDouble()
}
How to convert string to double in swift
Value of optional type 'Double?' not unwrapped; did you mean to use '!' or '?'?
This error appears because you are trying to add an optional value to total
.
Double(item)
produces an optional result so you can add it in if-let chain.
if let item = value as? String, let doubleVal = Double(item) {
total += doubleVal
}
Converting String to Double/Float loses precision for large numbers in Swift 5
If you want to keep your floating precision you need to use Decimal type and make sure to use its string initializer:
let value = "0.0000335651599321165"
if let decimal = Decimal(string: value) {
print(decimal)
}
This will print:
0.0000335651599321165
edit/update:
When displaying your value to the user with a fixed number of fraction digits you can use Number Formatter and you can choose a rounding mode as well:
extension Formatter {
static let number = NumberFormatter()
}
extension Numeric {
func fractionDigits(min: Int = 6, max: Int = 6, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
let value = "0.0000335651599321165"
if let decimal = Decimal(string: value) {
print(decimal.fractionDigits()) // "0.000034\n"
}
convert array of string into Double in swift
I will talk about convert an Array
of String
to Array
of Double
.
In swift Array
has a method called map
, this is responsable to map the value from array, example, in map function you will receive an object referent to your array, this will convert this object to your new array ex.
let arrOfStrings = ["0.3", "0.4", "0.6"];
let arrOfDoubles = arrOfStrings.map { (value) -> Double in
return Double(value)!
}
The result will be
UPDATE:
@LeoDabus comments an important tip, this example is considering an perfect datasource, but if you have a dynamic source you can put ?
on return and it will work, but this will return an array with nil
like that
let arrOfStrings = ["0.3", "0.4", "0.6", "a"];
let arrOfDoubles = arrOfStrings.map { (value) -> Double? in
return Double(value)
}
Look this, the return array has a nil
element
If you use the tips from @LeoDabus you will protect this case, but you need understand what do you need in your problem to choose the better option between map
or compactMap
example with compactMap
let arrOfStrings = ["0.3", "0.4", "0.6", "a"];
let arrOfDoubles = arrOfStrings.compactMap { (value) -> Double? in
return Double(value)
}
look the result
UPDATE:
After talk with the author (@davidandersson) of issue, this solution with map ou contactMap isn't his problem, I did a modification in his code and work nice.
first I replaced var message = "" per var rateValue:Double = 0.0 and replaced
Floatto
Double`
look the final code
let url = URL(string: "https://www.x-rates.com/calculator/?from=EUR&to=USD&amount=1")!
let request = NSMutableURLRequest(url : url)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
var rateValue:Double = 0.0;
if let error = error {
print(error)
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
var stringSeperator = "<span class=\"ccOutputRslt\">"
if let contentArray = dataString?.components(separatedBy: stringSeperator){
if contentArray.count > 0 {
stringSeperator = "<span"
let newContentArray = contentArray[1].components(separatedBy: stringSeperator)
if newContentArray.count > 0 {
rateValue = Double(newContentArray[0])! + 10
}
}
}
}
}
//
print("Rate is \(rateValue)"); //Rate is 11.167
}
task.resume()
Hope to help you
String to Double conversion nil in different region Swift
Careful handling of localized numeric strings
let inputString = "12,8"
let formatter = NumberFormatter()
formatter.locale = Locale.current // Locale(identifier: "de")
let number = formatter.number(from: inputString)
print(number) // 12.8
Related Topics
Wait Until Swift For Loop With Asynchronous Network Requests Finishes Executing
Difference Between a Weak Reference and an Unowned Reference
Using Decodable in Swift 4 With Inheritance
How to Compare One Value Against Multiple Values - Swift
What Does a Module Mean in Swift
Passing Lists from One Function to Another in Swift
Does Swift Copy on Write For All Structs
How to Fix Cocoapod .Modulemap File Not Found
Getting a "This Application Is Modifying the Autolayout Engine from a Background Thread" Error
Flatten an Array of Arrays in Swift
Differences in Nsdatecomponents Syntax
How to Make a Random Color With Swift
Arkit - What Do the Different Columns in Transform Matrix Represent