Question

- (void)textFieldDidEndEditing:(UITextField *)textField

{
    if (textfield1) {

        NSString *txt = self.textfield1.text;

        double num1 = [txt doubleValue];

        double tCost = num1 /100;

        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

        [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];


        NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];

        self.textfield1.text = [NSString stringWithFormat:@"%0.@",numberAsString];
    }
}

This is the code ive put together it formats the output of a textfield into currency im trying to work out how do format the currency so the output is,

if someone types in 1625 it formats it as 0.1625 currently if somone types in 50 it formats it as 0.50 which is correct as it supposed to be a calculator which is taking in peoples electricity rates which is either in cents or pences.

Was it helpful?

Solution 2

  • (void)textFieldDidEndEditing:(UITextField *)textField

{ if (textfield1) {

    NSString *txt = self.textfield1.text;

    double num1 = [txt doubleValue];


    double tCost = num1/100;





    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];


    //  NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];

    //NSString *numberAsString = [numberFormatter stringFromNumber:
    //                      [NSNumber numberWithDouble:[tCost doubleValue]]];



    [numberFormatter setMaximumFractionDigits:3];

    [numberFormatter setRoundingMode: NSNumberFormatterRoundUp];

    NSString *numberString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:tCost]];


    self.textfield1.text = [NSString stringWithFormat:@"%@",numberString];
}

}

OTHER TIPS

To get currency formatting use the following code :

- (NSString*) getAmountInCurrencyFormatWithValue:(NSString*) valueString {

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[valueString doubleValue]]];

    return numberAsString;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top