0

the problem is found in a class i write,i found the 19.8851 past to the %f,only get 19.88509,is this because the float cant save too mush fractional part?

//
//  main.m
//  0.6 the_float_not_corrert
//
//  Created by Sen on 7/4/14.
//  Copyright (c) 2014 SLboat. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 *  for get a float value from function
 *
 *  @return a flaot value
 */
float getafloat(){

    return 19.8851;
}

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"const 19.8851 is %f",19.8851);
        NSLog(@"19.8851 is %f",getafloat());
        float byValue = 19.8851;
        NSLog(@"19.8851 pass in value is %f",byValue);

    }
    return 0;
}

this is what i got

2014-07-04 09:42:07.508 0.6 the_float_not_corrert[11540:303] const 19.8851 is 19.885100
2014-07-04 09:42:07.510 0.6 the_float_not_corrert[11540:303] 19.8851 is 19.885099
2014-07-04 09:42:07.511 0.6 the_float_not_corrert[11540:303] 19.8851 pass in value is 19.885099
Program ended with exit code: 0
slboat
  • 502
  • 6
  • 14

3 Answers3

2

float are typically implemented using the IEEE 754-2008 the 32-bit base 2 format call binary32

As this format is based on powers-of-2 and not powers-of-10 the value of 19.8851 is not exactly representable. The 2 closest choices are

19.8850994110107421875 (closest to 19.8851)
19.885101318359375

The closest value was returned from getafloat().

When this value is printed, unless otherwise stated, is printed to 6 places past the decimal point which is

  19.885099
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • @slboat Note: as a reference, an answer (in C) about displaying FP may be of use: http://stackoverflow.com/questions/16839658/printf-width-specificer-to-maintain-precision-of-floating-point-value/19897395#19897395 – chux - Reinstate Monica Jul 04 '14 at 18:00
1

On a computer, the float 19.8851 really is the same as the float 19.885099. That is how computer decimal number storage works. That is why you would never compare them using ==. You would compare them to within some small epsilon; for example:

if (fabsf(f1 - f2) < 0.0001) { // close enough, they count as equal
matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Have you tried like using %.4f ?

Have look at below example:

@autoreleasepool {

    NSLog(@"const 19.8851 is %.4f",19.8851);
    NSLog(@"19.8851 is %.4f",[self getafloat]);
    float byValue = 19.8851;
    NSLog(@"19.8851 pass in value is %.4f",byValue);  
}

Output:

2014-07-03 20:53:34.297 TestApp[721:907] const 19.8851 is 19.8851
2014-07-03 20:53:34.304 TestApp[721:907] 19.8851 is 19.8851
2014-07-03 20:53:34.305 TestApp[721:907] 19.8851 pass in value is 19.8851
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56