Search code examples
iphoneiosalphamasktogglebutton

how would i set this app up to accept localized currency and output to that currency


Hi I'm trying to set up localization to my app, it currently recieves strings from a textbox, and converts them to a double. Then it proceeds to do a calculation and output that as a string onto the screen

What I am trying to do is, have the app know they are from a particular country convert the string to local currency , do the calculations, then output it in the relevant currency,

I think the solution lies nsformatter. I have been looking through documentation and im lost, here is my code, what would you guys suggest any help would be welcome.

(IBAction)calculateCost:(UIButton *)sender {

   NSString *rate = self.textField1.text;
   NSString *wat = self.textField2.text;
   NSString *hours = self.textField3.text;
   NSString *Days = self.textField4.text;

   double num1 = [rate doubleValue];
   double num2 = [wat doubleValue];
   double num3 = [hours doubleValue];
   double num4 = [Days doubleValue];

   double appKw = num2 / 1000;
   double costKwph = appKw *num1;

   double tCost = ((num4 * num3) * costKwph);

   if (num2 == 0 ||  num1 == 0 || num3 == 0 || num4 == 0) {
      self.textField5.text = 0;
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"oops" message:@"you must fill in all fields" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
      [alert show];
   }
   tCost = tCost / 100;

   self.textField5.text = [NSString stringWithFormat:@"£%0.2f",tCost];

}

Solution

  • NSNumberFormatter includes a currency style, which is locale-safe, but not thread-safe, so they should't be modified from different threads. An example follows:

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:tCost/100.00]];