Search code examples
objective-cmacoscocoanstextfield

NSTextField: integerValue behaving inconsistently


I have found that [NSTextField integerValue] behaves differently with values containing thousands separators depending on how the value was set.

(I am in Germany, so my thousands separator in these examples is a point ".").

  • If I call [myTextField setIntegerValue:4567], the text field will contain 4.567 (with tousands separator), and [myTextField integerValue] returns 4567.

  • If I type the value 4.567 info the text field manually, or use [myTextField setStringValue:@"4.567"], then [myTextField integerValue] returns just 4.

Apparently it stops parsing the number at the thousands separator, even though it inserts such a separator itself when calling setIntegerValue.

So I have actually two questions:

  1. Is there a setting or other easy way that I can prevent it to format the number when using -setIntegerValue: ?
  2. Can I "enable" the number parsing to understand/accept thousands separators when calling -integerValue? Or, if not, what would be the simplest way to parse a number with thousands separator from an NSString?

Solution

  • Add a Number Formatter (NSNumberFormatter) to the text field in the storyboard or XIB. This makes the contents of the cell and objectValue of the text field a NSNumber instead of a NSString.

    Is there a setting or other easy way that I can prevent it to format the number when using -setIntegerValue: ?

    Switch off Grouping Separator of the formatter.

    Can I "enable" the number parsing to understand/accept thousands separators when calling -integerValue?

    Switch on Grouping Separator of the formatter and set Primary Grouping to 3.

    Or, if not, what would be the simplest way to parse a number with thousands separator from an NSString?

    Use a NSNumberFormatter, see the class reference and Number Formatters.