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;
}
How can this be made less ugly?
if (truncatedValue[2]>='5') totalsum++;
\$\endgroup\$roundUpto2digit(1)
? \$\endgroup\$if
statement including only the MSB will do it. Thanks! \$\endgroup\$roundUpto2digit(999)
? Following your code the result will be 100. But this is a 3-digit integer. Is this okay or should it be further truncated to 10 to make a 2-digit integer? \$\endgroup\$