-1

I am getting an unusal issue with float in Objective C. I enter 100.1 and i get 100.100002 shouldn't it be something like 100.100000 .

Following is the code

float temp=100.1;
NSLog(@"%f",temp); 

100.100000

Can someone guide me what am i doing wrong or how to fix it ? I cannot use fixed decimal places i-e i cannot just use 100.10 . I need all decimal places .

Faizan Tanveer
  • 335
  • 6
  • 17
  • 2
    The summary of the floating-point tag says “If your question is about small arithmetic or decimal conversion errors, please read the "learn more..." page linked below”. http://stackoverflow.com/questions/tagged/floating-point – Pascal Cuoq May 02 '15 at 22:42
  • You should never use float until you can tell us a good reason why you are not using double. – gnasher729 May 03 '15 at 00:01
  • @gnasher729 - And you should never use double until you know what "floating point" means. – Hot Licks May 03 '15 at 01:06

2 Answers2

1

Because that is a fundamental part of what happens when you represent an arbitrary floating point value in binary. The number of binary digits is limited, therefore rounding occurs. Depending on your needs, you might be better off using NSDecimalNumber.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
-1

Try using double instead;

double temp=100.1;
NSLog(@"%.8f",temp);

100.10000000

It is an issue with representation accuracy. I do not think it will be a problem to use double instead.

aytunch
  • 1,326
  • 1
  • 16
  • 31