Is there an API for this? Or maybe a better way of doing it?
Here's what I'm trying to acomplish:
In is a numeric string. Out, is a NSDecimalNumber
// this one is for US:
in: 1 out: 0.01
in: 12 out: 0.12
in: 123 out: 1.12
// a diferent locale might have a diferent maximumFractionDigits, like 1
in: 1 out: 0.1
in: 12 out: 1.2
in: 123 out: 12.3
// other locales might have 0, or 3 fraction digits.
Here's how I have it:
// Clear leading zeros
NSNumber *number = [formatter numberFromString:numericString];
numericString = [formatter stringFromNumber:number];
if (maximumFractionDigits == 0) {
return [NSDecimalNumber decimalNumberWithString:numericString];
}
else if (numericString.length <= _currencyFormatter.maximumFractionDigits) {
NSString *zeros = @"";
for (NSInteger i = numericString.length; i < maximumFractionDigits ; i++) {
zeros = [zeros stringByAppendingString:@"0"];
}
return [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"0.%@%@",zeros,numericString]];
} else {
NSString *decimalString = [NSString stringWithFormat:@"%@.%@",
[_rateInput substringToIndex:numericString.length - maximumFractionDigits],
[_rateInput substringFromIndex:numericString.length - maximumFractionDigits]];
return [NSDecimalNumber decimalNumberWithString: decimalString];
}
While this does seem to work, I was wondering if there is an API for this, or a more simple, less error prone way of doing it?