Converting a String to a Double

I am trying to create an app which takes in the amount of money and tells you how much you have. But to display it correctly I need to convert what they type into a number. How do I convert a string into a double or a number?

Answered by MrIrazak in 730480022

Hey,

Check this:

let number = 100

let string = "100"



    //Prints number as a string

print(String(number))



    //prints Number as String

print(Int(string))



    //Prints Number as a Double

print(Double(number))



let converted = Int(string) ?? 100

    // without the ?? optional unwrapping you will get an optional output. Givt it a default value in case nothing comes back.



    //prints converted number 

print(converted)

Hope this helps.

Best, Imran

Accepted Answer

Hey,

Check this:

let number = 100

let string = "100"



    //Prints number as a string

print(String(number))



    //prints Number as String

print(Int(string))



    //Prints Number as a Double

print(Double(number))



let converted = Int(string) ?? 100

    // without the ?? optional unwrapping you will get an optional output. Givt it a default value in case nothing comes back.



    //prints converted number 

print(converted)

Hope this helps.

Best, Imran

Converting a String to a Double
 
 
Q