0

I try to convert my string data to float type. Conversion works but I need exact value.

Here is my code and output;

let myString = "2558.40";
let convertedToFloat = (myString as NSString).floatValue

// convertedToFloat is 2558.3999

So, I need exactly 2558.40 as float type. What should I do?

Fatih TAN
  • 778
  • 1
  • 5
  • 23
  • 1
    Maybe? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Robert Dresler Jan 06 '19 at 18:57
  • Anyway, don't use `NSString`, use native Swift type `String` (so you don't have to convert it) and then just convert your string to `Float`: `let convertedToFloat = Float(myString)!` (or you can choose some safer method of optional unwrapping) – Robert Dresler Jan 06 '19 at 18:59
  • @RobertDresler Float(myString)! is still "2558.3999" – Fatih TAN Jan 06 '19 at 19:00
  • I didn't say that this would solve your problem, this is just an advice. – Robert Dresler Jan 06 '19 at 19:01
  • Floating point representation on 32 or 64 bits (or even more bits) can't express all decimal number.You could try `let formatter = NumberFormatter(); let n = formatter.number(from: myString)!` – ielyamani Jan 06 '19 at 19:02
  • @Carpsen90 I get this: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. – Fatih TAN Jan 06 '19 at 19:15
  • @FatihTAN I used forced unwrapping (`!`) for brevity, you should make sure that the string can be converted to a number with optional binding or guard – ielyamani Jan 06 '19 at 19:17
  • @Carpsen90 formatter.number(from: "2558.40") gives me nil. Are you sure, number() function returns float type. – Fatih TAN Jan 06 '19 at 19:19
  • @FatihTAN No it return an NSNumber – ielyamani Jan 06 '19 at 19:20
  • It's the answer pointed out by @RobertDresler states, it's not possible to exact represent that number. However, you might want to look into using `Double` or `Decimal`. For instance: `let convertedToDouble = Double(myString)!` `let convertedToDecimal = Decimal(myString)!` – alanpaivaa Jan 06 '19 at 20:15

0 Answers0