IS there any easier way to show $ currency format?

2020-04-23 06:02发布

问题:

I using X code 4.

And Making an US Currency Calculator.

My Aim is to display the numbers in proper format?

Like

$ 1,234

$12,100

$1,23,123

I dont want do this by appending , and string stuff.

Is there any easier way so that I can integrate any RE or any ruby or Python. Which will help me to make currency format.

Please show me easier way rather than long programming.

回答1:

The NSNumberFormatter allows you to format currency. Example taken from [iOS developer:tips];

// Create formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];  
//--------------------------------------------
// Format style as currency, output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithInt:1234]];
NSLog(@"Output as currency: %@", formattedOutput);

//--------------------------------------------
// Change local and output as currency
//--------------------------------------------
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"it_IT"];
[formatter setLocale:locale];
formattedOutput = [formatter stringFromNumber:[NSNumber numberWithInt:1234]];
NSLog(@"Output as currency - locale it_IT: %@", formattedOutput);

[locale release];
[formatter release];


回答2:

Found this answer here: Objective-C: How to format string as $ Price

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];

By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.