I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
This is building upon the answer by @Ryu
His solution is great as long as you're in a country where dots are used as separators. By default
NSNumberFormatter
uses the devices locale. Therefore this will fail in all countries where a comma is used as the default separator (including France as @PeterK. mentioned) if the number uses dots as separators (which is normally the case). To set the locale of this NSNumberFormatter to be US and thus use dots as separators replace the linewith
Therefore the full code becomes
To use this, just call
"Your text goes here".toDouble()
This will return an optional
Double?
As @Ryu mentioned you can either force unwrap:
or use an
if let
statement:Swift :- 4
There are possibly two ways to do this:
String -> Int -> Double:
String -> NSString -> Double
Use it anyway you like according to you need of the code.
Swift 4.0
try this
On SWIFT 3, you can use:
Note: - If a string contains any characters other than numerical digits or locale-appropriate group or decimal separators, parsing will fail. - Any leading or trailing space separator characters in a string are ignored. For example, the strings “ 5”, “5 ”, and “5” all produce the number 5.
Taken from the documentation: https://developer.apple.com/reference/foundation/numberformatter/1408845-number
As of Swift 1.1, you can directly pass
String
toconst char *
parameter.If you don't like deprecated
atof
:One caveat: the behavior of conversion is different from
NSString.doubleValue
.atof
andstrtod
accept0x
prefixed hex string:If you prefer
.doubleValue
behavior, we can still useCFString
bridging:SWIFT 4