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){
// rounds to 100(3 digit) if cents in range [990,999]
if (cents >= 990 && cents <= 999 ) return 99;
// 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=0;
if (truncatedValue.length()>2){
// if the second digit is zero, return the first multiplied by 10
if (truncatedValue[1]=='0') return int(truncatedValue[0]-'0')*10;
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++;
}
else{
// if 2 digit no rounding needed
return cents;
}totalsum;
}
How can this be made less ugly?