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.
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.
You can remove trailing zeros using TRIM() function.
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.
Use the following:
NSString* floatString = [NSString stringWithFormat:@"%g", myFloat];
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
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