开发者

How to use NSNumberFormatter for currency to print in UITextField

I am a N00b here .

I print my currency like this :

-(IBAction)buttonPressed1:(id)sender
    {
        double currency = [Amount1.text doubleValue] + [Amount2.text doubleValue]; 
        SumCurrency.text = [NSString stringWithFormat:@"%0.0f", answer];
    }

I just simply want to use NSSNumberFormatter to print the SumCurrency.text in US Currency format .. Having a lot of trouble with it ..Please hekp

same issue ??? http://groups.jonzu.com/z_apple_using-a-nsnumberformatter-with-a-uitextfield.html

开发者_运维问答

Thanks in Advance .

Regards , N00b


I got the answer .. But for anyone's future reference

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

or, in Swift:

let amount = 123.56
let formatter = NumberFormatter()
formatter.locale = Locale.current
// or
// f.locale = Locale(identifier: "it_IT")
formatter.numberStyle = .currency

let formattedAmountSting = formatter.string(for: amount)!


This is an example of a situation where categories in Objective-C shine.

The cleanest solution is to create a category for NSNumber. .h:

@interface NSNumber (Formatter)

- (NSString *)currencyStringValue;

@end

and .m:

@implementation NSNumber (Formatter)

- (NSString *)currencyStringValue
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.locale = [NSLocale currentLocale];
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;

    return [formatter stringFromNumber:self];
}

@end

In your code, you'd have to #import "NSNumber+Formatter.h" and simply do this:

- (IBAction)buttonPressed1:(id)sender
{
    double total = [Amount1.text doubleValue] + [Amount2.text doubleValue];
    NSNumber *totalNumber = [NSNumber numberWithDouble:total];
    SumCurrency.text = totalNumber.currencyStringValue;
}

Very clear and clean.


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 ; ) */


Using float or double (floating point arithmetic) with money is a very bad idea because precision errors. You should use fixed-point arithmetic, aka NSDecimalNumber.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜