-3

I wrote a sample to convert string to float in Objective-C:

NSString *sampleFloatString = @"1.3";
float sampleFloatValue = [sampleFloatString floatValue];

But when I display sampleFloatValue, it shows '1.29999995'. I know it's equal to 1.3, but why is it not exactly '1.3'? Why do we need to format it explicitly? Is there any other way of doing this conversion?

Jamal
  • 763
  • 7
  • 22
  • 32
Ashok
  • 5,585
  • 5
  • 52
  • 80

3 Answers3

3

Its called "Floating point error". The way that computers represent decimal numbers causes them to not be 100% accurate all the time:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Dan F
  • 17,654
  • 5
  • 72
  • 110
2

Try this

float sampleFloatValue = (float) sampleFloatString;

Hope it helps.

Pradumna Patil
  • 2,180
  • 3
  • 17
  • 46
1

if you just wants to show these value somewhere than u can do these and it shows 1.3 exact..

NSString *sampleFloatString = @"1.3";
float sampleFloatValue = [sampleFloatString floatValue];
NSLog(@"%.1f",sampleFloatValue);
krushnsinh
  • 874
  • 1
  • 10
  • 11