2011-07-25 87 views
13

我有一個NSNumberFormatter,我試圖用來從NSNumber生成GBP(£)的整數。無論我嘗試使用哪種咒語,我都會得到兩位小數。我的代碼是:防止小數與NSNumberFormatter

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 
+5

我想獲得的intValue將刪除小數部分 – sujith1406

回答

35

我想你想調用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 
8

你可以嘗試以下

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

獲取從NSNumberintValue通過@Praveen

+1

感謝,通過設置minimumFractionDigits和maximumFractionDigits爲零我得到了我所需要的。 – Echilon

0

的建議你可以刪除所有NSNumberFormatter(這是相當密集的)只是這樣做:

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

格式字符串到小數點後兩位。(就是我正在尋找),適於...

  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]; 

好運