I believe this is a common pattern... We got something similar (but in C, and with decimal, so it is much more ugly) :
AmountToStr(char* Str,long long Amount, int NbDecimals){
sprintf(Str,"%lld",Amount);
int Length = strlen(Str);/* Apply scale down */
if (abs(Amount) >= 1000){
switch (NbDecimals){
case 0:
/* Delete the 2 decimals */
Str[Length-2] = '\0';
break;
case 2:
Str[Length] = Str[Length-];
Str[Length-1] = Str[Length-2];
Str[Length-2] = '.';
Str[Length+1] = '\0';
break;
case 3:
/* Add a decimal*/
Str[Length] = Str[Length-1];
Str[Length-1] = Str[Length-2];
Str[Length-2] = '.';
Str[Length+1] = '0';
Str[Length+2] = '\0';
break;
default:
/* Should not happen */
puts("!!! Nb of decimals to display must be 0, 2 or 3\n");
break;
}
}
else {
if (abs(Amount) >= 100){
switch (NbDecimals){
case 0:
/* Delete the 2 decimals */
Str[Length] = Str[Length-2];
Str[Length-1] = '.';
Str[Length-2] = '0';
break;
case 2:
Str[Length+1] = Str[Length-1];
Str[Length] = Str[Length-2];
Str[Length-1] = '.';
Str[Length-2] = '0';
Str[Length+2] = '\0';
break;
case 3:
Str[Length+1] = Str[Length-1];
Str[Length] = Str[Length-2];
Str[Length-1] = '.';
Str[Length-2] = '0';
Str[Length+2] = '0';
Str[Length+3] = '\0';
break;
default:
/* Should not happen */
puts("!!! Nb of decimals to display must be 0, 2 or 3\n");
break;
}
}
else {
switch (NbDecimals){
case 0:
/* Delete the 2 decimals: amount value is 0 */
Str[Length-1] = '0';
Str[Length] = '\0';
break;
case 2:
Str[Length+2] = Str[Length-1];
Str[Length+1] = '0';
Str[Length] = '.';
Str[Length-1] = '0';
Str[Length+3] = '\0';
break;
case 3:
Str[Length+2] = Str[Length-1];
Str[Length+1] = '0';
Str[Length] = '.';
Str[Length-1] = '0';
Str[Length+3] = '0';
Str[Length+4] = '\0';
break;
default:
/* Should not happen */
puts("!!! Nb of decimals to display must be 0, 2 or 3\n");
break;
}
}
}
break;
}
I let you check that it does not work in some cases...
Fortunaly, the guy who committed this is not there anymore.
Here's what was intended:
AmountToStr(char* Str,long long Amount, int NbDecimals){
switch(NbComDecimals){
case 0:snprintf(Str, AMOUNT_LENGTH, "%lld",Amount/100);
break;
case 1:snprintf(Str, AMOUNT_LENGTH, "%lld.%1lld",Amount/100,abs(Amount/10)%10);
break;
case 2:snprintf(Str ,AMOUNT_LENGTH,"%lld.%02lld",Amount/100,abs(Amount)%100);
break;
case 3:snprintf(Str ,AMOUNT_LENGTH, "%lld.%02lld0",Amount/100,abs(Amount)%100);
break;
default:puts("Wrong nb of decimal);}