Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to convert a NSString to its currency equivalent in Cocoa

Tags:

cocoa

I have a NSString value of @"78000". How do I get this in currency format, i.e. $78,000 with it remaining an NSString.

like image 692
Ta01 Avatar asked Feb 13 '09 01:02

Ta01


2 Answers

You need to use a number formatter. Note this is also how you would display dates/times etc in the correct format for the users locale

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

// set options.
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];

NSNumber *amount = [NSNumber numberWithInteger:78000];

// get formatted string
NSString* formatted = [currencyStyle stringFromNumber:amount]

[currencyStyle release];
like image 180
Andrew Grant Avatar answered Sep 20 '22 06:09

Andrew Grant


The decimal/cents at the end can be controlled as follows:

[currencyStyle setMaximumFractionDigits:0];

Here's the documentation link from apple

like image 24
tbone Avatar answered Sep 22 '22 06:09

tbone