I have a textfield that will hold only numbers. I need the numbers to adhere to the to have a maximum of 3 significant figures and a maximum of 2 decimal places. I also need to keep the original value and would only like to change the way the value is displayed. I am temporarily solving the issue by splitting the number up at the decimal point and removing more than 2 decimals but I would love to use NSNumberFormatter and remove that code. Here is what I'm trying to do:
NSNumber *customCalculation = @(0.04791234);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesSignificantDigits:YES];
[formatter setMaximumSignificantDigits:3];
[formatter setMaximumFractionDigits:2];
customTextField.text = [formatter stringFromNumber: customCalculation];
The output is: 0.0479. Not sure where I am making my mistake.
0.0479has 3 significant digits as you've instructed the formatter to display. Significant digits are the digits after the leading zeros.That'll give
0.05. To get0.04as the output, you'll need to change the rounding behaviour as well (because0.04791234should be0.05at 2dp precision).Yields
0.04.