Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 384
user2933653 Avatar asked Oct 29 '13 19:10

user2933653


People also ask

How do I print a float without zeros?

Use str.format(float) with str as the format specifier "{:g}" to return a string representation of float without trailing zeroes.

How do I get rid of trailing zeros?

A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.

How do you get rid of double trailing zeros?

format(doubleVal); // This ensures no trailing zeroes and no separator if fraction part is 0 (there's a special method setDecimalSeparatorAlwaysShown(false) for that, but it seems to be already disabled by default).


1 Answers

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

like image 93
Joel Fischer Avatar answered Nov 14 '22 23:11

Joel Fischer