I have a floating point value, but when i need to represent to the user I need it to show to one decimal place, without rounding off. so basically i need to truncate to up to one decimal place. for example 95.56 -> 95.5
Asked
Active
Viewed 2,100 times
-1
-
[find answer here][1] [1]: http://stackoverflow.com/questions/560517/how-to-set-the-float-value-to-two-decimal-number-in-objective-c – Saqib Saud Feb 16 '12 at 07:03
-
@SaqibSaud, all these answer in that page will round off the value, but i dont want to round off – cocoaNoob Feb 16 '12 at 07:29
3 Answers
6
NSNumberFormatter
will do this for you.
-setMaximumFractionDigits:
-setRoundingMode:
Update
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSNumberFormatter * nf = [[NSNumberFormatter new] autorelease];
[nf setMaximumFractionDigits:1];
[nf setRoundingMode:NSNumberFormatterRoundFloor];
NSLog(@"The number is '%@'", [nf stringFromNumber:[NSNumber numberWithDouble:95.56]]);
}
return 0;
}
Yields:
2012-02-16 02:39:49.799 NumberFormatter[14592:903] The number is '95.5'

justin
- 104,054
- 14
- 179
- 226
-
-
-
-
are you sure? that would be a bug (unless another trait is interfering) – justin Feb 16 '12 at 07:31
-
(In response to deleted response) At your suggestion, I did try it myself. It worked as I expected. See the update. – justin Feb 16 '12 at 07:42
-
sorry my mistake, it works like a charm, thank you, can u care to explain me the explaination, what is going on in behind – cocoaNoob Feb 16 '12 at 07:44
-
you're welcome. There are a few rounding modes -- `NSNumberFormatterRoundFloor ` rounds similar to the C math function `floor(double)` *however* the formatter will scale the argument for the fraction digits. – justin Feb 16 '12 at 07:46
-
but this approach has one problem if value is 16.8, then it will give result 16.7 – cocoaNoob Feb 17 '12 at 07:25
-
that's floating point behavior in C languages! - a floating point number is not a string, and it's not exact. if you `printf` a `float` representing `16.8`, you may see `16.799999`. `floor` that memory representation, and you have `16.7`. – justin Feb 17 '12 at 08:35
-
5
try out with this example
float t = 25.55;
NSLog(@"%.1f", t);
it shows 25.5 if you set %.2f you get 25.55

Hiren
- 12,720
- 7
- 52
- 72
-
if here t =25.56, then it shows 25.6, rather i want to show 25.5 only – cocoaNoob Feb 16 '12 at 07:27
1
It should be like this
sudo code
convert number to string.
find "." in string.
make a substring from start to "." position +1

Saqib Saud
- 2,799
- 2
- 27
- 41
-
Even I was thinking that way, but number formatter is better solution, and performance wise is better compare to string manipulation – cocoaNoob Feb 17 '12 at 05:38