用NSNumberFormatter防止小数
我有一个NSNumberFormatter,我试图用来从一个NSNumber生成一个GBP(£)的整数。 无论我尝试哪种咒语,我都会得到两位小数。 我的代码是:
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
我想你想调用setMaximumFractionDigits为零。
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
你可以尝试以下
[fmtCurrency setGeneratesDecimalNumbers:NO]; [fmtCurrency setMaximumFractionDigits:0];
要么
按照@Praveen的build议从NSNumber
获取intValue
你需要从NSNumber中提取intValue 。
你可以删除所有的NSNumberFormatter(这是相当密集的),只是:
txtTotal.text = [NSString stringWithFormat:@"£%d", result.Bill.intValue];
格式string到两位小数…(正是我正在寻找)适应…
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];
祝你好运