I recently needed to create a function that took an NSString as the input number and then another to specify the number of decimal places it was to be returned with and I thought I’d share. (in reality it expanded to also handle any multiplication and division I needed also).
It’s quite short but the awkwardness was in getting StringWithFormat to output what I needed.
+(NSString *) returnNumber:(NSString *)numberIn toDecimalPlaces:(NSString *)decimalPlaces
{
// Assign the right number of decimal places:
decimalPlaces = [NSString stringWithFormat:@"%%.%@f", decimalPlaces];
NSString* result = [NSString stringWithFormat:decimalPlaces, numberIn];
return result;
}
Here’s the expanded function managing everything I needed at the time:
+(NSString *) multiplyThenDivide:(NSString *)numberIn by:(NSString *)multiplicationFactorIn divideBy:(NSString *)divisionFactor toDecimalPlaces:(NSString *)decimalPlaces
{
// Make arguments into floats so we can do operations on them:
float numberInFloat = [numberIn floatValue];
float multiplicationInFloat = [multiplicationFactorIn floatValue];
// Do those operations:
float resultFloat = numberInFloat * multiplicationInFloat;
resultFloat = resultFloat / 100;
// Assign the right number of decimal places:
decimalPlaces = [NSString stringWithFormat:@"%%.%@f", decimalPlaces];
NSString* result = [NSString stringWithFormat:decimalPlaces, resultFloat];
return result;
}
By no means a master class, but hopefully it’ll help someone at some point.