Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSString to currency format

Tags:

ios

In Java we do this statement to have a $ currency format.

    double num1 = 3.99 ;       
    double num2 = 1.00 ;       
    double total = num1 + num2;

    System.out.printf ("Total: $ %.2f", total);

The result is:

Total: $4.99

//--------------------------------

Now in iOS how can I get same format if I have the following statement :

total.text = [NSString stringWithFormat:@"$ %d",([self.coursePriceLabel.text intValue])+([self.courseEPPLabel.text intValue])+10];

Note:
If I use doubleValue the output always is 0 .

like image 453
NamshanNet Avatar asked Dec 15 '22 21:12

NamshanNet


1 Answers

You can do the same thing with NSString:

NSString *someString = [NSString stringWithFormat:@"$%.2lf", total];

Note that the format specifier is "%lf" rather than just "%f".

But that only works for US dollars. If you want to make your code more localizable, the right thing to do is to use a number formatter:

NSNumber *someNumber = [NSNumber numberWithDouble:total];

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *someString = [nf stringFromNumber:someNumber];

Of course, it won't do to display a value calculated in US dollars with a Euro symbol or something like that, so you'll either want to do all your calculations in the user's currency, or else convert to the user's currency before displaying. You may find NSValueTransformer helpful for that.

like image 112
Caleb Avatar answered Dec 30 '22 09:12

Caleb