Incorrect Decimal Formatting NSNumberFormatter

198 views Asked by At

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.

1

There are 1 answers

0
rickerbh On BEST ANSWER

0.0479 has 3 significant digits as you've instructed the formatter to display. Significant digits are the digits after the leading zeros.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];

That'll give 0.05. To get 0.04 as the output, you'll need to change the rounding behaviour as well (because 0.04791234 should be 0.05 at 2dp precision).

NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setRoundingMode:NSNumberFormatterRoundDown];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];

Yields 0.04.