1

I am trying to convert string to float but it changes the decimal values. e.g I have a string:

NSString *str = @"33.641832";
float value = [str floatValue]; //33.6418304

the value give me 33.6418304 instead of 33.641832. I want to convert exactly as in the string.

Eiko
  • 25,601
  • 15
  • 56
  • 71
Wasim Ahmed
  • 358
  • 3
  • 19

2 Answers2

1

This is due to the lack of float precision.

By my experience, Float are precise to the 7 significant digit approximatly.

33.641832 is stored as 33641832 *10^-6 so you have 8 significant digit (33641832).

You should use double if you want more precision.

Florian Burel
  • 3,408
  • 1
  • 19
  • 20
  • The number is actually stored in binary, not decimal. – Simon Byrne Aug 15 '16 at 13:34
  • @SimonByrne Huh? Are you serious? – Droppy Aug 15 '16 at 13:36
  • @SimonByrne yes obviously, but it is store on 4 bytes: 1 bit for the sign, 8 for the exp value (base), and 22 bits for the significant digit. More info : https://en.wikipedia.org/wiki/Single-precision_floating-point_format. – Florian Burel Aug 15 '16 at 13:37
  • Yes, see https://en.wikipedia.org/wiki/Single-precision_floating-point_format – Simon Byrne Aug 15 '16 at 13:38
  • It is actually stored as `1.051307201385498046875 * 2^5` – Simon Byrne Aug 15 '16 at 13:40
  • well it is stored as 0 and 1, we can all agree to that. we are all grown up dev here. so obviously, int float double, string, object, pointers are stored as binary. what I mean is that in order to "represent" the idea of decimal (you cannot cut a bit) the pattern used is to mutliply the decimal by a power of ten until you obtain the smallest integer (called the fraction). the fraction is stored as a binary in a part of the 4 bytes and the power of ten (called the base) is stored in another – Florian Burel Aug 15 '16 at 13:43
  • My point was that the exponent is stored as a power of 2, not 10. – Simon Byrne Aug 15 '16 at 19:49
0

See the table in this post by Rick Regan:

A float type is only guaranteed to accurately "round-trip" numbers with 6 significant digits. For doubles, the guarantee is 15.

Simon Byrne
  • 7,694
  • 1
  • 26
  • 50