Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 547
user74756e61 Avatar asked Mar 15 '14 03:03

user74756e61


People also ask

How do I print float values without trailing zeros?

To format floats without trailing zeros with Python, we can use the rstrip method. We interpolate x into a string and then call rstrip with 0 and '. ' to remove trailing zeroes from the number strings. Therefore, n is 3.14.

How do you get rid of trailing zeros in decimal?

You can remove trailing zeros using TRIM() function.

What is the rule for trailing zeros?

To determine the number of significant figures in a number use the following 3 rules: Non-zero digits are always significant. Any zeros between two significant digits are significant. A final zero or trailing zeros in the decimal portion ONLY are significant.


2 Answers

Use the following:

NSString* floatString = [NSString stringWithFormat:@"%g", myFloat];
like image 154
user3488205 Avatar answered Sep 28 '22 05:09

user3488205


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
like image 31
Marcelo Fabri Avatar answered Sep 28 '22 03:09

Marcelo Fabri