ios numberformatter currency remove trailing decimals if 0 -


i want format number currency string. these following cases

25.00 => $25 25.43 => $25.43 25.4 => $25.40 0.00 -> $0 

is there way in nsnumberformatter?

this code right now:

nsnumberformatter *fmt = [[nsnumberformatter alloc] init]; [fmt setnumberstyle:nsnumberformattercurrencystyle]; [fmt setcurrencycode:@"usd"]; 

however fails first , last examples.

i tried:

nsnumberformatter *fmt = [[nsnumberformatter alloc] init]; [fmt setpositiveformat:@"$0.##"]; 

however fails third case. suggestions?

i don't think there's way using plain nsnumberformatter. set minimum , maximum fraction digits 0 formatting integers in subclass of nsnumberformatter:

@interface mycurrencyformatter : nsnumberformatter @end  @implementation mycurrencyformatter  - (id)init {     if ((self = [super init])) {         [self setnumberstyle:nsnumberformattercurrencystyle]];         [self setcurrencycode:@"usd"];     }     return self; }  - (nsstring *)stringfromnumber:(nsnumber *)anumber {     nsinteger minimumfractiondigits = [self minimumfractiondigits];     nsinteger maximumfractiondigits = [self maximumfractiondigits];     if ([self isinteger:anumber]) {         [self setminimumfractiondigits:0];         [self setmaximumfractiondigits:0];     }     nsstring *formattednumber = [super stringfromnumber:anumber];     [self setminimumfractiondigits:minimumfractiondigits];     [self setmaximumfractiondigits:maximumfractiondigits];     return formattednumber; }  - (bool)isinteger:(nsnumber *)anumber {     nsdecimal decimalvalue = anumber.decimalvalue;     nsdecimalround(&decimalvalue, &decimalvalue, 0, nsrounddown);     nsdecimalnumber *roundedvalue = [[nsdecimalnumber alloc] initwithdecimal:decimalvalue]     return [anumber isequaltonumber:roundedvalue];     }  @end 

this should handle international number formats well.

credit this post determining if number integer.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -