在Cocoa应用程序中,我使用了大量“带有数字格式化器的文本字段”对象。这些对象通过在适当的位置添加逗号来改进数据的表示,因此数字“123456”表示为“123,456”。当数字是浮点类型时,这很有用,并使用以下代码填充:
[OutR2C2 setFloatValue:MyVariable2 ];
嗯,数字“123456.567”表示为“123,456.567”,数字“123456.5”表示为“123,456.5”。
我需要能够指定小数点后总是有两位数,如123,456.50或123,456.56等所示的所有数字。在这个对象的属性中,我没有看到任何设置小数点的方法。
如何在使用“带数字格式化程序的文本字段”对象时执行此操作?
答案 0 :(得分:2)
你可能有这样的事情:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
其次是:
[formatter setFormat:@"###.##"];
您需要将其切换为:
[formatter setFormat:@"###.00"];
这将使您的数字始终显示两位小数。
或者您也可以使用:
[formatter setFormat:@"##0.00"];
如果要在小数点前显示0,如果它是< 1值。 (例如.44将显示为0.44)。
答案 1 :(得分: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];
}
答案 2 :(得分: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的Custom类。那就像[formatter setFormat:@"##0.00"];
有关详细信息,请https://developer.apple.com/documentation/foundation/numberformatter