2

Please look at the code below and the result in console.

NSString *strRatio = @"0.03" ;
float f = [strRatio floatValue] ;
NSLog(@"%f, %@", f, f == 0.03 ? @"equal" : @"not equal") ;

result:

0.030000, not equal

Also I have a screenshot when I add a breakpoint at NSLog(@"%f, %@", f, f == 0.03 ? @"equal" : @"not equal") ; , it gives me a different value of f showing 0.0299999993...

Can anyone explain it ?

  1. Why is the result of f == 0.03 is false ?
  2. Why the value of f printed is 0.030000 but it shows 0.0299999993 when debug.

enter image description here

Edit :

I expect that the value of f is 0.03 after converting from @"0.03", how can I achieve it ?

It seems that float can't represent 0.03. Even if I assign 0.03 to float value forcibly, I will get 0.029999993 as the result.

KudoCC
  • 6,722
  • 1
  • 21
  • 48
  • 1
    `float` uses a binary representation and *cannot* represent 0.03. The first part of your question is a duplicate of [strange output in comparison of float with float literal](http://stackoverflow.com/questions/1839422/strange-output-in-comparison-of-float-with-float-literal). - See also [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Martin R Apr 22 '14 at 08:28
  • Thanks a lot. It is very helpful. – KudoCC Apr 22 '14 at 08:34

2 Answers2

1

The value is not 0.03, it is as shown in the debugger - 0.0299999993.

It shows as 0.03000 in the log because by default, %f shows 5 decimal places so the value 0.0299999993 is being rounded to 0.03000.

Change the log to use %.10f and you will see the real value.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
1

Try NSDecimalNumber instead of [string floatValue];

NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:@"0.03"];

NSLog(@"number1: %@", number1); //0.03
Dili
  • 2,229
  • 3
  • 24
  • 38
  • `f = [number1 floatValue] ; NSLog(@"number1: %.10f", f) ;` still get 0.029999993... – KudoCC Apr 22 '14 at 07:05
  • "Exact float value from a NSString" Not easily. It's entirely possible that the number represented in the NSString has no exact representation as a primitive floating-point type. Refer Question :http://stackoverflow.com/questions/6888509/exact-float-value-from-a-nsstring – Dili Apr 22 '14 at 07:09
  • NSLog(@" Number1 : %.2f",f); You will get 0.03. Or use NSDecimalNumber, its a class given like NSNumber which is normally used in such instances. – Dili Apr 22 '14 at 07:11