user3186310
user3186310

Reputation: 149

Remove trailing zeros of a double only when necessary

Im making a calculator app and I am using a double for the precision. I didn't want the extra zeros and the decimal to be displayed so I changed the place holder token to "%.f". Because I did this if I do a problem on the calculator that does involve decimals they don't show up.

My question is basically if there is any way to have the %.f be used only when its necessary. If there is no way, what do you recommend doing to make it so I only have a decimal when its actually needed. Thanks.

Upvotes: 0

Views: 710

Answers (2)

zaph
zaph

Reputation: 112857

For a calculator consider using NSDecimalNumber combined with NSNumberFormatter. There are going to be lot's of problems using floating point. Consider: (2 / 3.000000001) * 3.000000001, the result will not necessarily be exactly 2.

Upvotes: 2

ansible
ansible

Reputation: 3579

You probably want to use NSDecimarlNumber, but to answer your question, you can user NSNumberFormatter to format the output for a double.

double someNumber = 1.9;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSLog(@"%@",[formatter stringFromNumber:[NSNumber numberWithDouble:someNumber]]);

My output

2014-01-13 11:30:41.429 DTMTestApp[23933:907] 1.9

Upvotes: 3

Related Questions