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]&gt;=5) totalsum++; 
    return totalsum;
} 


How can this be made less ugly?
If I understood your requirements correctly then it might be like this:

int roundUpto2digit(int cents) {
  if (cents &lt; 100)
    return cents &lt; 10 ? cents * 10 : cents;
  while ((cents + 5) &gt;= 1000)
    cents /= 10;
  return (cents + 5) / 10;
}


The test:

#include &lt;stdio.h&gt;

void
test(int i) {
    printf("%d -&gt; %d\n", i, roundUpto2digit(i));
}

int
main() {
    test(0);
    test(1);
    test(5);
    test(9);
    test(10);
    test(49);
    test(50);
    test(94);
    test(95);
    test(99);
    test(100);
    test(104);
    test(105);
    test(994);
    test(995);
    test(999);
    test(1000);
    test(1040);
    test(1050);
    return 0;
}


The result:

0 -&gt; 0
1 -&gt; 10
5 -&gt; 50
9 -&gt; 90
10 -&gt; 10
49 -&gt; 49
50 -&gt; 50
94 -&gt; 94
95 -&gt; 95
99 -&gt; 99
100 -&gt; 10
104 -&gt; 10
105 -&gt; 11
994 -&gt; 99
995 -&gt; 10
999 -&gt; 10
1000 -&gt; 10
1040 -&gt; 10
1050 -&gt; 11


It is uncertain if [1, 9] range should map into [10, 90] (2 digits) or [1, 9] (1 digit). I could fix it, if the later case is true.