user2933653 user2933653 - 2 years ago 66
iOS Question

How to not show unnecessary zeros when given integers but still have float answers when needed

I have an app I'm developing and one of my features is giving answers in float or double values when needed and an integer when the answer is a whole number

so for example if the answer comes out to 8.52 the answer becomes 8.52 but when the answer is 8 the answer is 8 instead of 8.0000, i don't want it to show all the extra 0s.

- (IBAction) equalsbutton {
NSString *val = display.text;
switch(operation) {

case Plus :
display.text= [NSString stringWithFormat:@"%qi",[val longLongValue]+[storage longLongValue]];

case Plus2 :
display.text= [NSString stringWithFormat:@"%f",[val doubleValue]+[storage doubleValue]];

this code doesn't seem to work

Answer Source

These specifiers are standard IEEE format specifiers, which means that you can do things like %.2f to only show 2 decimal places on a float variable.

You could also convert it into an int, and then use the %d format specifier if you wanted to do it that way.

Here's also Apple's documentation on the subject.

EDIT: Based on your comment on the other post, it looks like you're looking for %g, which will essentially remove the extraneous 0's from floats.

display.text= [NSString stringWithFormat:@"%g",[val doubleValue]+[storage doubleValue]];

I found the answer here: Use printf to format floats without decimal places if only trailing 0s

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download