NSString %f Truncate 0s

Discussion in 'iOS Development' started by Old_Man_Willow, Jan 20, 2010.

  1. Old_Man_Willow

    Old_Man_Willow New Member

    Joined:
    Aug 7, 2009
    Messages:
    9
    Likes Received:
    0
    Device:
    iPod touch
    Hey, just a quick question here. I'm writing a program that outputs a float variable to a label, which I'm using the code:
    [OBJC]
    myLabel.text = [NSString stringWithFormat

    Please Register or Log in to view images

    "%f", myFloat];
    [/OBJC]
    Where myLabel is a label and myFloat is a float variable. What I'm wondering is if there is a way to truncate the zeros that appear at the end, because currently it outputs values like: 49.50000. Any help?
  2. Axis

    Axis Super Moderator Staff Member

    Joined:
    Dec 2, 2007
    Messages:
    6,288
    Likes Received:
    133
    Device:
    iPhone 4S (White)
    The %f format specifier has a few tricks.

    If you wanted to cut down your output to, say, the hundredths, you would do:

    ...[NSString stringWithFormat

    Please Register or Log in to view images

    "%.2f", myFloat];

    You would then see values like 49.50, or 34.56, or 12.00
  3. Old_Man_Willow

    Old_Man_Willow New Member

    Joined:
    Aug 7, 2009
    Messages:
    9
    Likes Received:
    0
    Device:
    iPod touch
    What would I do if I have a variable amount of non-zero numbers after the decimal? For example, if I wanted to display 1.450000 as 1.45 and 1.765600 as 1.7656.
  4. Axis

    Axis Super Moderator Staff Member

    Joined:
    Dec 2, 2007
    Messages:
    6,288
    Likes Received:
    133
    Device:
    iPhone 4S (White)
    [OBJC]
    int variable_width;
    // do whatever necessary to calculate the width
    myLabel.text = [NSString stringWithFormat

    Please Register or Log in to view images

    "%.*f", variable_width, myFloat];
    [/objc]

    If you mean limiting only zeros, use %g

    [objc]
    printf("%g", 4.30000); // 4.3
    printf("%g", 4.3456000); // 4.3456
    [/objc]

Share This Page