Search code examples
objective-cmathroundingfloor

Objective-C: Flooring to 3 decimals correctly


I am trying to floor a float value to the third decimal. For example, the value 2.56976 shall be 2.569 not 2.570. I searched and found answers like these:

floor double by decimal place

Such answers are not accurate. For example the code:

double value = (double)((unsigned int)(value * (double)placed)) / (double)placed

can return the value - 1 and this is not correct. The multiplication of value and placed value * (double)placed) could introduce something like: 2100.999999996. When changed to unsigned int, it becomes 2100 which is wrong (the correct value should be 2101). Other answers suffer from the same issue. In Java, you can use BigDecimal which saves all that hassels.

(Note: of course, rounding the 2100.9999 is not an option as it ruins the whole idea of flooring to "3 decimals correctly")


Solution

  • I had to consider a solution involving NSString and it worked like a charm. Here is the full method:

    - (float) getFlooredPrice:(float) passedPrice {
    
        NSString *floatPassedPriceString = [NSString stringWithFormat:@"%f", passedPrice];
        NSArray *floatArray = [floatPassedPriceString componentsSeparatedByString:@"."];
        NSString *fixedPart = [floatArray objectAtIndex:0];
        NSString *decimalPart = @"";
        if ([floatArray count] > 1) {
            NSString *decimalPartWhole = [floatArray objectAtIndex:1];
            if (decimalPartWhole.length > 3) {
                decimalPart = [decimalPartWhole substringToIndex:3];
            } else {
                decimalPart = decimalPartWhole;
            }
        }
        NSString *wholeNumber = [NSString stringWithFormat:@"%@.%@", fixedPart, decimalPart];
    
        return [wholeNumber floatValue];
    
    }