ram ram -4 years ago 98
Objective-C Question

How to trim zeros after decimal point

I am trying to trim zeros after a decimal point as below but it's not giving desired result.

trig = [currentVal doubleValue];
trig = trig/100;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
display.text = [formatter stringFromNumber:[NSNumber numberWithDouble:trig]];


The number is still being displayed without trimming zeros after the decimal point.

Here
currentVal
is the number I am entering.

For example if i pass "trig" = 123 (Initially "trig" = 123 after doing trig/100 i want to display 1.23 but it is displaying as 1.23000000).

Answer Source

From the documentation, it looks like setFractionDigits: is only for converting the other way.

The best thing to do is probably to convert your number to an integer before formatting it e.g.

 double converted = round(trig); // man round for docs

You can use also the formatting functions of stringWithFormat: of NSString, but then you will lose all the localisation advantages you get with NSNumberFormatter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download