我在这里是N00b。
我这样打印我的货币:
-(IBAction)buttonPressed1:(id)sender
{
double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];
SumCurrency.text = [NSString stringWithFormat:@"%0.0f", answer];
}
我只是想使用NSSNumberFormatter以美国货币格式打印SumCurrency.text。它有很多麻烦..请使用hekp
同样的问题??? http://groups.jonzu.com/z_apple_using-a-nsnumberformatter-with-a-uitextfield.html
先谢谢。
问候, N00b
答案 0 :(得分:17)
我得到了答案..但是对于任何人未来的参考
-(IBAction)buttonPressed1:(id)sender {
double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:currency]];
SumCurrency.text = [NSString stringWithFormat:@"Converted:%@",numberAsString];
}
或者,在Swift中:
let amount = 123.56
let formatter = NSNumberFormatter()
formatter.locale = NSLocale.currentLocale()
// or
// f.locale = NSLocale(localeIdentifier: "it_IT")
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let formattedAmountSting = formatter.stringFromNumber(amount)
答案 1 :(得分:4)
这是Objective-C中的类别闪耀的情况的一个例子。
最干净的解决方案是为NSNumber创建一个类别。 .H:
@interface NSNumber (Formatter)
- (NSString *)currencyStringValue;
@end
和.m:
@implementation NSNumber (Formatter)
- (NSString *)currencyStringValue
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
return [formatter stringFromNumber:self];
}
@end
在您的代码中,您必须#import“NSNumber + Formatter.h”并执行此操作:
- (IBAction)buttonPressed1:(id)sender
{
double total = [Amount1.text doubleValue] + [Amount2.text doubleValue];
NSNumber *totalNumber = [NSNumber numberWithDouble:total];
SumCurrency.text = totalNumber.currencyStringValue;
}
非常清晰干净。
答案 2 :(得分:1)
NSNumberFormatter * fmt;
NSNumber * n;
fmt = [ [ NSNumberFormatter alloc ] init ];
n = [ NSNumber numberWithFloat: 10 ];
[ fmt setFormatterBehavior: NSNumberFormatterBehavior10_4 ];
[ fmt setCurrencySymbol: @"$" ];
[ fmt setNumberStyle: NSNumberFormatterCurrencyStyle ];
NSLog( @"%@", [ fmt stringFromNumber: n ];
[ fmt release ] /* Thanx willcodejavaforfood... My mistake ; ) */
答案 3 :(得分:-1)
使用float或double(浮点运算)和钱是一个非常糟糕的主意,因为精度错误。你应该使用定点算术,也就是NSDecimalNumber。