2012-06-27 52 views
1

在Cocoa應用程序中,我使用了大量「帶有數字格式程序的文本字段」對象。這些對象通過在適當的地方添加逗號來改善數據的顯示,因此數字「123456」顯示爲「123,456」。這是有幫助的當數用下面的代碼爲float類型,並填充:用數字格式化程序指定文本字段中的小數位數

[OutR2C2 setFloatValue:MyVariable2 ]; 

那麼,數字「123456.567」是作爲「123,456.567」和數字「123456.5」是作爲「123,456.5 「。

我需要能夠指定小數點後總是有兩位數字,如123,456.50或123,456.56等所有提供的數字。在這個對象的屬性中,我沒有看到任何設置小數點的方法。

如何在使用「帶有數字格式化程序的文本字段」對象時執行此操作?

回答

2

你可能有這樣的事情:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

其次是這樣的:

[formatter setFormat:@"###.##"];

你需要切換,爲:

[formatter setFormat:@"###.00"];

這會使您的數字始終顯示兩位小數。

或者您可以使用:

[formatter setFormat:@"##0.00"];

如果你想顯示0之前小數點,如果它是一個< 1的值。 (例如.44將顯示爲0.44)。

1

我很感謝在這個問題上的幫助。回覆幫助我找到了如下所示的解決方案。我將它發佈爲問題的答案,以便可以幫助其他人提出相同的問題

在此示例中,文檔上有兩個NSTextField對象,並由Interface Builder以.xib文件顯示。

在.h文件,在@interface部分...

@interface MyViewController : NSWindowController { 
@private 

    IBOutlet NSTextField *Out1; 
    IBOutlet NSTextField *Out2; 

// other code goes here 

} 



In the .m file, in the @implementation section… 


    @implementation MyViewController 

    -(void)awakeFromNib 
    { 

    // set decimal places 

     NSNumberFormatter *numberFormatter = 
     [[[NSNumberFormatter alloc] init] autorelease]; 
     NSMutableDictionary *newAttributes = [NSMutableDictionary dictionary]; 

     [numberFormatter setFormat:@"###,##0;(###,##0)"]; 
    //[numberFormatter1 setFormat:@"###,##0.00;(###,##0.00)"]; // for two decimal places. 


     [newAttributes setObject:[NSColor redColor] forKey:@"NSColor"]; 
     [numberFormatter setTextAttributesForNegativeValues: newAttributes]; 


     [[Out1 cell] setFormatter:numberFormatter]; 
     [[Out2 cell] setFormatter:numberFormatter]; 



    } 
0

我也很欣賞這兩個答案和解決方案。

對於那些在Swift中尋找解決方案的人來說,這裏可能就是其中之一。

class NumberFormatterWithFraction_2 : NumberFormatter { 

    required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 

    minimumIntegerDigits = 1 
    minimumFractionDigits = 2 
    maximumFractionDigits = 2 
    roundingMode = .halfDown 
    } 

} 

然後,在最近的Xcode的Interface Builder中指定上面定義的類作爲Number Formatter的自定義類。這將類似於[formatter setFormat:@"##0.00"];

有關詳細信息,https://developer.apple.com/documentation/foundation/numberformatter

相關問題