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).
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
}
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()
}
xcode: need to convert strings to double and back to string
In Swift 2 there are new failable initializers that allow you to do this in more safe way, the Double("")
returns an optional in cases like passing in "abc"
string the failable initializer will return nil
, so then you can use optional-binding
to handle it like in the following way:
let s1 = "4.55"
let s2 = "3.15"
if let n1 = Double(s1), let n2 = Double(s2) {
let newString = String( n1 - n2)
print(newString)
}
else {
print("Some string is not a double value")
}
If you're using a version of Swift < 2, then old way was:
var n1 = ("9.99" as NSString).doubleValue // invalid returns 0, not an optional. (not recommended)
// invalid returns an optional value (recommended)
var pi = NSNumberFormatter().numberFromString("3.14")?.doubleValue
Swift 4 - Convert string in double value with NSString
Don't do that.
Basically you can bridge cast String
to NSString
let nsString = "12.34" as NSString
print(nsString.doubleValue)
rather than using an initializer (the error message says there is no appropriate initializer without a parameter label), but casting to NSString
to get the doubleValue
is the wrong way in Swift.
Get the String
, use the Double
initializer and unwrap the optionals safely
if let lat = array[indexPath.row]["lat"] as? String,
let latAsDouble = Double(lat) {
// do something with latAsDouble
}
swift: issue in converting string to double
There are two different issues here. First – as already mentioned in
the comments – a binary floating point number cannot represent the
number 8.7
precisely. Swift uses the IEEE 754 standard for representing
single- and double-precision floating point numbers, and if you assign
let x = 8.7
then the closest representable number is stored in x
, and that is
8.699999999999999289457264239899814128875732421875
Much more information about this can be found in the excellent
Q&A Is floating point math broken?.
The second issue is: Why is the number sometimes printed as "8.7"
and sometimes as "8.6999999999999993"?
let str = "8.7"
print(Double(str)) // Optional(8.6999999999999993)
let x = 8.7
print(x) // 8.7
Is Double("8.7")
different from 8.7
? Is one more precise than
the other?
To answer these questions, we need to know how the print()
function works:
- If an argument conforms to
CustomStringConvertible
, the print function calls itsdescription
property and prints the result
to the standard output. - Otherwise, if an argument conforms to
CustomDebugStringConvertible
,
the print function calls isdebugDescription
property and prints
the result to the standard output. - Otherwise, some other mechanism is used. (Not imported here for our
purpose.)
The Double
type conforms to CustomStringConvertible
, therefore
let x = 8.7
print(x) // 8.7
produces the same output as
let x = 8.7
print(x.description) // 8.7
But what happens in
let str = "8.7"
print(Double(str)) // Optional(8.6999999999999993)
Double(str)
is an optional, and struct Optional
does not
conform to CustomStringConvertible
, but toCustomDebugStringConvertible
. Therefore the print function calls
the debugDescription
property of Optional
, which in turn
calls the debugDescription
of the underlying Double
.
Therefore – apart from being an optional – the number output is
the same as in
let x = 8.7
print(x.debugDescription) // 8.6999999999999993
But what is the difference between description
and debugDescription
for floating point values? From the Swift source code one can see
that both ultimately call the swift_floatingPointToString
function in Stubs.cpp, with the Debug
parameter set to false
and true
, respectively.
This controls the precision of the number to string conversion:
int Precision = std::numeric_limits<T>::digits10;
if (Debug) {
Precision = std::numeric_limits<T>::max_digits10;
}
For the meaning of those constants, see http://en.cppreference.com/w/cpp/types/numeric_limits:
digits10
– number of decimal digits that can be represented without change,max_digits10
– number of decimal digits necessary to differentiate all values of this type.
So description
creates a string with less decimal digits. That
string can be converted to a Double
and back to a string giving
the same result.debugDescription
creates a string with more decimal digits, so that
any two different floating point values will produce a different output.
Summary:
- Most decimal numbers cannot be represented exactly as a binary
floating point value. - The
description
anddebugDescription
methods of the floating
point types use a different precision for the conversion to a
string. As a consequence, - printing an optional floating point value uses a different precision for the conversion than printing a non-optional value.
Therefore in your case, you probably want to unwrap the optional
before printing it:
let str = "8.7"
if let d = Double(str) {
print(d) // 8.7
}
For better control, use NSNumberFormatter
or formatted
printing with the %.<precision>f
format.
Another option can be to use (NS)DecimalNumber
instead of Double
(e.g. for currency amounts), see e.g. Round Issue in swift.
Swift double to string
It is not casting, it is creating a string from a value with a format.
let a: Double = 1.5
let b: String = String(format: "%f", a)
print("b: \(b)") // b: 1.500000
With a different format:
let c: String = String(format: "%.1f", a)
print("c: \(c)") // c: 1.5
You can also omit the format
property if no formatting is needed.
How can I convert String to Double without losing precision in swift
What you want to use is NSString(format:)
for the visual format of your value.
Swiftstub sample
To always show 2 digits visually use this:
NSString(format: "%.2f", value)
String to Double and leading whitespace
This is fully documented. Look at the documentation for the init
method that takes a StringProtocol
.
Near the end of all of the examples, it states:
Passing any other format or any additional characters as
text
results innil
. For example, the following conversions result innil
:Double(" 5.0") // Includes whitespace
So your solution to trim whitespace before conversion is the correct one.
Related Topics
Detect When Uitableviewcell Did Load
-[Uithreadsafenode Canperformaction:Withsender:]: Unrecognized Selector Sent to Instance
Avmutablevideocomposition Output Video Shrinked
Firebase Get Child Id Swift iOS
Openurl in Appdelegate Conversion Error Nsstring -> String (Swift & iOS8)
App Crash on Device But Works on Simulator iOS
How to Send Msmessage in Messages Extension
How to Display Only Limited Photos with PHPickerviewcontroller
Saving Already Created Live Photos
Value of Type 'Error' Has No Member 'Code'
How to Monitor More Than 20 Regions
Nsubiquityidentitydidchangenotification and Sigkill
Settitletextattributes Doesn't Work for Uitabbaritem When It Is Unselected in Swift