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
Use str.format(float) with str as the format specifier "{:g}" to return a string representation of float without trailing zeroes.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With