float converting and truncating

Discussion in 'iOS Programming' started by erdinc27, Jul 15, 2016.

  1. erdinc27 macrumors regular

    Jul 20, 2011
    i have a float value
    e.g : 3.92199993
    i want to truncate it like 3.921 what i did is to convert it to NSString with format 0.3f and have it what i want in string type. But when i convert that string to a float then it becomes like 3.92156863
    So what i can have 3.921 from the first float ?
  2. AxoNeuron, Jul 15, 2016
    Last edited: Jul 15, 2016

    AxoNeuron macrumors 65816


    Apr 22, 2012
    The Left Coast
    That solution sounds really slow. I'd suggest multiplying it by some number to get it to be > 1000, convert it to an Int (to lose the rest of the decimal precision), convert it back to a Float, and then divide it by that number.

    However if you insist on using NSString, you can do this to specify the precision:

    NSString *numberRep = [NSString stringWithFormat:@"%.4f", number];
    let numberRep = NSString(format: "%.4f", numberRep);
    Floating point math is complicated. The code above will let you guarantee a specific level of precision, but when you perform operations on the resulting numbers you will encounter floating point error to some degree. It's the same reason you will sometimes see 1.9999998998 instead of 2.00000000 for example.

    If you want to make explicitly certain that you will never have any floating point error problems, then don't use floating point variables. Multiply them by some set value, convert them to an Int, then deal with them as Int's. That way you can avoid floating point error. When you are ready to display them to the user, just divide by the set value and convert back to Floats.
  3. chown33 macrumors 604

    Aug 9, 2009
    3.92199993 is much closer to 3.922 than it is to 3.921. So printing 3.921 is arguably worse (less accurate).

    Example code and output:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main(int argc, const char * argv[])
        float f1 = 3.922f;
        printf( " f1: %.10f, %.3f\n", f1, f1 );
        float f2 = 0;
        sscanf( "3.921", " %f ", &f2 );
        printf( " f2: %.10f, %.3f\n", f2, f2 );
        return 0;
    ## Output
     f1: 3.9219999313, 3.922
     f2: 3.9210000038, 3.921
    Note the conversion of the string "3.921" did not result in 3.92156863. That would be an error of about 1 part in 10,000, which is much worse than one should be getting from float conversion.

    Post your code, or there's no way to guess why the result was 3.92156863.
  4. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Don't truncate until you display the result. Doing math with strings doesn't make sense.
  5. erdinc27 thread starter macrumors regular

    Jul 20, 2011
    thank you for your help guys. I made it by using NSNumberFormatter.

Share This Page