fbitterlich
fbitterlich

Reputation: 913

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 ".").

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?

Upvotes: 1

Views: 159

Answers (2)

Willeke
Willeke

Reputation: 15589

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.

Upvotes: 3

EmilioPelaez
EmilioPelaez

Reputation: 19882

integerValue is not locale-aware, it will always use . as the decimal point.

You should use NSNumberFormatter.numberFromString: instead.

Link to NSNumberFormatter class reference.

Upvotes: 2

Related Questions