Ziezi
Ziezi

Reputation: 6457

Truncating integer using string manipulation?

I have a class with a data member that needs to be rounded up to a 2 digit integer, irrespective of the number of the input digits.

For example:

roundUpto2digit(12356463) == 12 
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.

Currently my code looks like:

int roundUpto2digit(int cents){
    // convert cents to string
    string truncatedValue = to_string(cents);
    // take first two elements corresponding to the Most Sign. Bits
    // convert char to int, by -'0', multiply the first by 10 and sum the second 
    int totalsum =  int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
    // if the third element greater the five, increment the sum by one
    if (truncatedValue[2]>=5) totalsum++; 
    return totalsum;
} 

Any advice to make it less ugly will be deeply appreciated.

Upvotes: 0

Views: 89

Answers (2)

Equod
Equod

Reputation: 556

#include <math.h>

int roundUpto2digit(int value)
{
    value /= pow(10,(int)log10(value)-2);
    /*
    (int)log10(value) returns base ten logarithm (number of digits of your number)
    pow(10, N) returns number 1 followed by N zeros
    example:
    pow(10,(int)log10(123)-2) returns 1
    pow(10,(int)log10(1234)-2) returns 10
    pow(10,(int)log10(1234567)-2) returns 10000
    thus
    value / pow(10,(int)log10(value)-2) returns first 3 digits
    */
    return value%10>=5? (value+10)/10 : value/10;
    /*
    if(value%10>=5)// the last digit is >= 5
    {
    // increase previous number
    value = value + 10;
    }
    // return number without the last digit
    return value/10;
    */
}

Upvotes: 0

Samuel Navarro Lou
Samuel Navarro Lou

Reputation: 1188

You can use fixed point integer arithmetics which are probably faster and look better. You want the number in a scale of 10^2 and you have it in an arbitrary scale power of 10 as well, so to round you just need to apply the formula:

ROUNDED_VAL = (INITIAL_VAL + (10^(ORIG_SCALE - 2) / 2)) / 10^(ORIG_SCALE - 2)

So your code could look something like this:

int roundUpto2digit(int cents){
    int scale = 10;
    while(cents / scale > 0) {
        // Find out original scale. This can be done maybe faster with a divide and conquer algorithm 
        scale *= 10;
    }
    int applied_scale = scale / 100;
    if (applied_scale == 0) {
        // In case there is only one digit, scale it up to two
        return 10 * cents;
    }
    return ((cents + (applied_scale / 2)) / applied_scale);
} 

EDIT: The 10 * cents line I wrote was an arbitrary extrapolation of the problem I made based on my interpretation. If that is not the desired behavior, it can be of course changed.

Upvotes: 1

Related Questions