0

How to convert this type of string "8.37" to its decimal value 8.37? I'm using Swift 4.

I tried:

extension String {

func hexToFloat() -> Float {
    var toInt = Int32(truncatingIfNeeded: strtol(self, nil, 16))
    var float:Float32!
    memcpy(&float, &toInt, MemoryLayout.size(ofValue: float))
    return float
}
}

[...]

let myString = "8.37"
let myDecimal = myString.hexToFloat()
print(myDecimal) // prints 0.0

(From here)

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Tommy V.
  • 67
  • 7

1 Answers1

0

There's no straight forward way (at least to my knowledge). But you can do something like below to get the value. Please note that the code below is in Swift 3. You may have to change the syntax.

extension String {    
    func hexToFloat() -> Float {
        let data = myString.data(using: .utf8)
        let options: [String: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
        do {
            let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil)
            return Float(attributedString.string)!
        } catch {
            return 0
        }
    }
}

let myString = "8.37"
let myDecimal = myString.hexToFloat()
print(myDecimal) // prints 8.37
Malik
  • 3,763
  • 1
  • 22
  • 35
  • Thanks! Indeed, it works in Swift 3, but I have an error in Swift 4, even after applying the proposed fixes. The fixed code: `[...] let options: [String: Any] = [NSAttributedString.DocumentAttributeKey.documentType.rawVal‌​ue: NSAttributedString.DocumentType.html] [...]` The error at line 6: "Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedString.DocumentReadingOptionKey : Any]'" – Tommy V. Sep 04 '17 at 08:53
  • Try using this `let options: [String: Any] = [.documentType: NSAttributedString.DocumentType.html]` – Malik Sep 04 '17 at 09:10
  • Unfortunately, replacing `let options: [String: Any] = [NSAttributedString.DocumentAttributeKey.documentType.rawVal‌​‌​ue: NSAttributedString.DocumentType.html]` with `let options: [String: Any] = [.documentType: NSAttributedString.DocumentType.html]` didn't work. I have this error message in addition to the other one: "Type 'String' has no member 'documentType'" – Tommy V. Sep 04 '17 at 09:32
  • Sorry my bad. Remove the line `let options: [String: Any] = .....` completely and then replace the line `let attributedString = try...` with `let attributedString = try NSAttributedString(data: data!, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8], documentAttributes: nil)` – Malik Sep 05 '17 at 00:33
  • Thank you! It works, after adding `.rawvalue` to `.characterEncoding: String.Encoding.utf8`(see [here](https://stackoverflow.com/questions/39643394/swift-3-error-swiftvalue-unsignedintegervalue-unrecognized-selector).) – Tommy V. Sep 05 '17 at 05:49