Preventing decimals with NSNumberFormatter

可紊 提交于 2019-12-03 01:39:33
zpasternack

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

You can try the following

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

or

Get intValue from the NSNumber as suggested by @Praveen

You need to extract the intValue from NSNumber.

You could remove all the NSNumberFormatter (which is quite intensive) and just do:

txtTotal.text = [NSString stringWithFormat:@"£%d", result.Bill.intValue];

Swift 4

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 0

format string to two decimals... (was what i was searching) adapted...

            float distance = //distance with many decimals...;

            NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
            [numberFormatter setMaximumFractionDigits:2];

            //new distance with two decimals
            NSNumber* myNumber = [NSNumber numberWithFloat:distance];

good luck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!