user74756e61
user74756e61

Reputation: 221

How do I delete trailing zeros on floats without rounding in Objective-C?

I need to clear trailing zeros on floats without rounding? I need to only display relevant decimal places.

For example, if I have 0.5, I need it to show 0.5, not 0.500000. If I have 2.58328, I want to display 2.58328. If I have 3, I want to display 3, not 3.0000000. Basically, I need the amount of decimal places to change.

Upvotes: 17

Views: 7169

Answers (2)

user3488205
user3488205

Reputation: 367

Use the following:

NSString* floatString = [NSString stringWithFormat:@"%g", myFloat];

Upvotes: 30

Marcelo
Marcelo

Reputation: 9944

NSNumberFormatter is the way to go:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits = 20;

NSString *result = [formatter stringFromNumber:@1.20];
NSLog(@"%@", result);

result = [formatter stringFromNumber:@0.00031];
NSLog(@"%@", result);

This will print:

1.2
0.00031

Upvotes: 27

Related Questions