Convert NSString to Currency Format

In Java, we do this statement in order to have the $ currency format.

double num1 = 3.99 ; double num2 = 1.00 ; double total = num1 + num2; System.out.printf ("Total: $ %.2f", total); 

Result:

Total: $ 4.99

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

Now in iOS, how can I get the 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 is always 0.

+4
source share
1 answer

You can do the same with NSString:

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

Note that the format specifier is "% lf", not just "% f".

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

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

Of course, it will not display the value calculated in US dollars with the euro symbol or something like that, so you either want to do all your calculations in the user's currency, or convert it to the user before displaying. You can find NSValueTransformer .

+10
source

All Articles