Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly format currency on ios

I'm looking for a way to format a string into currency without using the TextField hack.

For example, i'd like to have the number "521242" converted into "5,212.42" Or if I have a number under 1$, I would like it to look like this: "52" -> "0.52"

Thanks

like image 365
François Marceau Avatar asked Aug 03 '12 00:08

François Marceau


People also ask

How do you Format Currency value?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.


1 Answers

You probably want something like this (assuming currency is a float):

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle]; NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:currency]]; 

From your requirements to treat 52 as .52 you may need to divide by 100.0.

The nice thing about this approach is that it will respect the current locale. So, where appropriate it will format your example as "5.212,42".

Update: I was, perhaps, a little speedy in posting my example. As pointed out by Conrad Shultz below, when dealing with currency amounts, it would be preferable to store the quantities as NSDecimalNumbers. This will greatly reduce headaches with rounding errors. If you do this the above code snippet becomes (assuming currency is a NSDecimalNumber*):

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle]; NSString *numberAsString = [numberFormatter stringFromNumber:currency]; 
like image 58
idz Avatar answered Oct 08 '22 02:10

idz