RE: NSNumberFormatter & Currency Symbol
RE: NSNumberFormatter & Currency Symbol
- Subject: RE: NSNumberFormatter & Currency Symbol
- From: "email@hidden" <email@hidden>
- Date: Tue, 11 Aug 2009 23:19:55 +0100
This is from a while back...
http://www.cocoabuilder.com/archive/message/cocoa/2008/11/18/223010
quote:
Is it possible to have a text field with a currency symbol that
appears automatically? For instance, if the user types 400, $400.00
appears in the text field. I've been using IB's formatter with 10.4+
and I don't see any options that would allow for this. As it stands,
if the formatter is configured for currency, the text field won't
allow an entry that doesn't start with a $.
The following method can be added to an NSNumberFormatter subclass to
provide the basic functionality described above.
Switching locales provides lots of variability in how an instance of
NSNumberFormatter is configured.
The method below only acts on positive prefixes and suffixes
sufficient for the likes of $1.00, £1.00 and 1,00 €.
Plenty of room for refinement.
/*
get object value for string
The default formatter behaviour will generate an error if the
currency symbol is omitted
from the input string.
To make life easy for the user we will prefix/suffix the currency
symbol if it is missing.
Note that some locales suffix the currency.
*/
- (BOOL)getObjectValue:(id *)obj forString:(NSString *)string
errorDescription:(NSString **)error
{
NSString *positivePrefix = [self positivePrefix];
NSString *positiveSuffix = [self positiveSuffix];
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet
whitespaceCharacterSet]];
NSScanner *scanner = [NSScanner scannerWithString:string];
// if positive prefix defined
if ([positivePrefix length] > 0) {
if (![scanner scanString:positivePrefix intoString:NULL]) {
string = [NSString stringWithFormat:@"%@%@", positivePrefix, string];
}
}
// if positive suffix defined
if ([positiveSuffix length] > 0) {
NSString *suffix = @"";
if ([string length] >= [positiveSuffix length]) {
NSUInteger index = [string length] - [positiveSuffix length];
suffix = [string substringFromIndex:index];
}
if (![suffix isEqualToString:positiveSuffix]) {
/* We can simply add suffix here even if it is a multicharacter
sequence (say spc-€).
If input is say 1€ our result is 1€ € but this parses okay.
1€ is deemed valid input and the remainder of the string is
discarded, whatever it is.
*/
string = [NSString stringWithFormat:@"%@%@", string, positiveSuffix];
}
}
return [super getObjectValue:obj forString:string
errorDescription:error];
}
Jonathan Mitchell
Developer
http://www.mugginsoft.com
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden