Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing decimals with NSNumberFormatter

I have an NSNumberFormatter which I'm trying to use to generate a whole number of GBP (£) from an NSNumber. I keep getting two decimal places regardless of which incantation I try. My code is:

NSNumberFormatter *fmtCurrency = [[[NSNumberFormatter alloc] init] autorelease];
[fmtCurrency setNumberStyle: NSNumberFormatterCurrencyStyle];
[fmtCurrency setGeneratesDecimalNumbers:FALSE];
[fmtCurrency setCurrencyCode:@"GBP"];
[fmtCurrency setCurrencySymbol:@"£"];
txtTotal.text = [fmtCurrency stringFromNumber: result.Bill ]; // this is an NSNumber
like image 549
Echilon Avatar asked Jul 25 '11 07:07

Echilon


4 Answers

I think you want to call setMaximumFractionDigits with zero.

NSNumberFormatter *fmtCurrency = [[[NSNumberFormatter alloc] init] autorelease];
[fmtCurrency setNumberStyle: NSNumberFormatterCurrencyStyle];
[fmtCurrency setGeneratesDecimalNumbers:NO];
[fmtCurrency setCurrencyCode:@"GBP"];
[fmtCurrency setCurrencySymbol:@"£"];

NSNumber* myNumber = [NSNumber numberWithFloat:12.34];
NSString* myString = [fmtCurrency stringFromNumber:myNumber];
NSLog( @"the number is %@", myString );

[fmtCurrency setMaximumFractionDigits:0];
myString = [fmtCurrency stringFromNumber:myNumber];
NSLog( @"now it's %@", myString );  


2011-07-25 01:05:39.823 FormatterTest[841:707] the number is £12.34
2011-07-25 01:05:39.824 FormatterTest[841:707] now it's £12
like image 71
zpasternack Avatar answered Oct 05 '22 16:10

zpasternack


You can try the following

[fmtCurrency setGeneratesDecimalNumbers:NO];
[fmtCurrency setMaximumFractionDigits:0];

or

Get intValue from the NSNumber as suggested by @Praveen

like image 20
visakh7 Avatar answered Oct 05 '22 17:10

visakh7


Swift 4

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 0
like image 38
IvanPavliuk Avatar answered Oct 05 '22 17:10

IvanPavliuk


You need to extract the intValue from NSNumber.

like image 44
Praveen S Avatar answered Oct 05 '22 16:10

Praveen S