Numeric Entry and Formatting With NSNumberFormatter Won't Append Zeros
Numeric Entry and Formatting With NSNumberFormatter Won't Append Zeros
- Subject: Numeric Entry and Formatting With NSNumberFormatter Won't Append Zeros
- From: Philip McIntosh <email@hidden>
- Date: Fri, 23 Sep 2011 17:48:55 -0600
I have a calculation project using buttons to input numbers into a UILabel. I want it to format the numbers as they are entered to display grouping separators. It has been a struggle but so far the best I have ben able to achieve is this (I got the basic idea from a post at stackoverflow.com):
NSString *currentText = [display_ text];
currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@""];
currentText = [currentText stringByReplacingOccurrencesOfString:@"." withString:@"."];
NSString *lastChar = [currentText substringFromIndex:[currentText length] - 1];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@","];
[formatter setDecimalSeparator:@"."];
[formatter setMaximumFractionDigits:20];
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:currentText];
NSString *finalText = [formatter stringFromNumber:number];
if ([lastChar isEqualToString:@"."])
{
finalText = [finalText stringByAppendingString:@"."];
}
[display_ setText: finalText];
[formatter release];
This code is called by a notification in my button input method. Integers like 2,000,000 work fine. Decimals like 234.56482 work fine. However It will not accept and display any decimals with zeros after the decimal point (like 2.0003 or 2.234076). When I try to extend the number string with a zero the button clicks but nothing happens. It only wants non-zeros. It's got me stumped.
_______________________________________________
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