Question

Merging these two strings:

@"###.##"
@"123"

Should output:

@"1.23"

I have developed a solution for this, but I'm looking for a simpler way, Using a NSNumberFormater, or some other API that I might be missing in Apple's documentation.

Thank you!

-

The solution as is right now, that I'm trying to get rid of:

/**
 *  User inputs a pure, non fractional, numeric string (e.g 1234) We'll see how many fraction digits it needs and format accordingly (e.g. 1234 produces a string such as '12.34' for 2 fractional digits. 12 will produce '0.12'.)
 *
 *  @return The converted numeric string in an instance of NSDecimalNumber
 */
- (NSDecimalNumber *)decimalNumberFromRateInput
{
    if (_numericInput == nil ||
        _numericInput.length == 0) {
        _numericInput = @"0";
    }

    [self clearLeadingZeros];

    if (self.formatter == nil) {
        return nil;
    }

    if (self.formatter.maximumFractionDigits == 0) {
        return [NSDecimalNumber decimalNumberWithString:_numericInput];
    }

    else if (_numericInput.length <= self.formatter.maximumFractionDigits) {

        NSString *zeros = @"";
        for (NSInteger i = _numericInput.length; i < self.formatter.maximumFractionDigits ; i++) {
            zeros = [zeros stringByAppendingString:@"0"];
        }

        NSString *decimalString = [NSString stringWithFormat:@"0.%@%@",zeros,_numericInput];
        return [NSDecimalNumber decimalNumberWithString:decimalString];

    }

    else {

        NSString *decimalPart       = [_numericInput substringToIndex:  _numericInput.length - self.formatter.maximumFractionDigits];
        NSString *fractionalPart    = [_numericInput substringFromIndex:_numericInput.length - self.formatter.maximumFractionDigits];
        NSString *decimalString     = [NSString stringWithFormat:@"%@.%@", decimalPart, fractionalPart];

        return [NSDecimalNumber decimalNumberWithString: decimalString];

    }

}
Was it helpful?

Solution

If I understand your goal correctly, the solution should be much simpler:

float number = [originalString floatValue] / 100.0;
NSString *formattedString = [NSString stringWithFormat:@"%.2f", number];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top