I feel like the answer is right in front of my face but I cannot seem to find it.

My code:

- (void)viewDidLoad {

    numFormatter = [[NSNumberFormatter alloc] init];
    numFormatter.locale = [NSLocale currentLocale];
    [numFormatter setMaximumFractionDigits:2];
    [numFormatter setDecimalSeparator:@"."];
    [numFormatter setAlwaysShowsDecimalSeparator:YES];
    [numFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
}

-(void)textFieldDidChange:(UITextField *)textField{

    inputLbl.text = [numFormatter stringFromNumber:[NSNumber numberWithDouble:[dummyTextField.text doubleValue]]];

}

If the user inputs 101, it displays as $101.00 when I need $1.01 so the input seems to start after the decimal point, when I want it start at the hundreds point of the decimals.

有帮助吗?

解决方案

NSNumberFormater takes in a number and formats that number according to whichever style you've set. If the user inputs 101, as you suggest, then one hundred and one is the number being formatted. You've selected the currency style, so you get $101.00. The number is still 101; it is just formatted to look like a currency amount.

If you want $1.01, you're going to have to input the number 1.01. The number formatter doesn't change the number. It just changes the way it's displayed. 1.01 is a number; $1.01 is that number represented as currency. 1.01 is not equal to 101. The number formatter doesn't change the number you input, just how it's displayed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top