-1

I can't convert string to double correctly.

enter image description here

I tried to convert string to double, but I couldn't convert it correctly and didn't know what the problem was.

  • OS : MacOS 12.6
  • CPU : Apple M1
  • Xcode : Version 14.0.1

how to convert string to double in swift

RIPSM S
  • 1
  • 1
  • use Double(string) to convert string to double. it will return you a optional double – Naqeeb Nov 02 '22 at 10:38
  • Please can you add some detail to your explanation and also some code. The debug display you have suggests it is converting correctly. If you are worried about why it says the `Double` is 56.1599..97, that's normal and it is because 56.16 cannot be expressed exactly as a binary floating point number. – JeremyP Nov 02 '22 at 10:42

1 Answers1

2

String is converting successfully but it is giving you approximate value based on value in String.

instead of doubleVlaue use Double initializer to convert string

Double(myString)

it will return you an option double. If the string contains invalid characters or invalid format it will return nil.

you can unwrap it like this

 if let convertedValue = Double(myString) {
    print("Value is \(convertedValue)")
} else {
    print("Not a valid number")
}
Naqeeb
  • 1,121
  • 8
  • 25
  • I tried what you said, but the result was the same. `Double("56.16")` I want to convert the string from 56.16 to double, but the result is still 56.159999999997. – RIPSM S Nov 02 '22 at 10:54
  • 1
    I just tried the same it is working fine for me check this question it might help https://stackoverflow.com/q/588004/6737277 – Naqeeb Nov 02 '22 at 11:02
  • Thank you for your help. I have to find a way to recalculate. – RIPSM S Nov 02 '22 at 11:16
  • @RawipasS 56.159999999997 _is_ 56.16 on a computer. You're getting the right answer for the string to double conversion. What you don't like is the way the double is being represented as a string! But that is a different matter. – matt Nov 02 '22 at 12:27