patterncppMinor
Truncating integer using string manipulation
Viewed 0 times
truncatingmanipulationusingstringinteger
Problem
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:
Currently my code looks like:
How can this be made less ugly?
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?
Solution
If I understood your requirements correctly then it might be like this:
The test:
The result:
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.
int roundUpto2digit(int cents) {
if (cents = 1000)
cents /= 10;
return (cents + 5) / 10;
}The test:
#include
void
test(int i) {
printf("%d -> %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 -> 0
1 -> 10
5 -> 50
9 -> 90
10 -> 10
49 -> 49
50 -> 50
94 -> 94
95 -> 95
99 -> 99
100 -> 10
104 -> 10
105 -> 11
994 -> 99
995 -> 10
999 -> 10
1000 -> 10
1040 -> 10
1050 -> 11It 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.
Code Snippets
int roundUpto2digit(int cents) {
if (cents < 100)
return cents < 10 ? cents * 10 : cents;
while ((cents + 5) >= 1000)
cents /= 10;
return (cents + 5) / 10;
}#include <stdio.h>
void
test(int i) {
printf("%d -> %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;
}0 -> 0
1 -> 10
5 -> 50
9 -> 90
10 -> 10
49 -> 49
50 -> 50
94 -> 94
95 -> 95
99 -> 99
100 -> 10
104 -> 10
105 -> 11
994 -> 99
995 -> 10
999 -> 10
1000 -> 10
1040 -> 10
1050 -> 11Context
StackExchange Code Review Q#85502, answer score: 6
Revisions (0)
No revisions yet.