Search code examples
loopsfor-loopcrystal-reportsinteger

Crystal Reports - Compounding Total in For Loop - Unexpected Results


I've been coding for 15 years, know many languages, C#, C++, PHP, PAWN, SMALL, ETC ETC. Crystal syntax is probably the most inconsistent and nonsensical I have ever seen.

Anyhow, I am trying to do something simple here. I have a string formatted like this in my db: "1-DESC, 2-OTHER, 5-MISC"

The '-' and ',' are delimeters for splitting the string up in my code. Anyhow I need to add 1+2+5 so that CR reports the total of those numbers. For some reason in following code I keep getting "30.00" when I should be getting 10. I can't make sense of how CR is doing this....

//create an array of strings by parsing a underscore-delimited string field
Stringvar Array strings := Split({Estim.User_Memo1}, ', ');

numbervar i; 
numbervar total = 0;
numbervar total2 = 0;
For i := 1 to count(strings) Do
( 
    If InStr(strings[i], '-') > 0 then 
    (
        Stringvar Array numdesc := Split(strings[i], '-');
        total2 := ToNumber(numdesc[1]);
        total := total + total2;
        //total := total + ToNumber(numdesc[1]);
    );
);

total;

My db input string being pulled is: "1-Cracked Head, 2-No Threads, 3-O/S Length, 4-U/S Length"

Excuse my redundant total variables. I have been trying to find workarounds for about an hour now.

Thanks for any insight.


Solution

  • first you need to assign the value the you need to use :.

    Now tor retrive the number you can use Val function which will return numbers from a string in number format which will make arithematic operations easy.

    Try this... Currently I don't have CR to test for syntax..but logic is something like this.

    //create an array of strings by parsing a underscore-delimited string field
    Stringvar Array strings := Split({Estim.User_Memo1}, ', ');
    
    numbervar i; 
    numbervar total:= 0;
    numbervar total2:= 0;
    For i := 1 to count(strings) Do
    ( 
    //    If InStr(strings[i], '-') > 0 then 
      //  (
        //    Stringvar Array numdesc := Split(strings[i], '-');
          //  total2 := ToNumber(numdesc[1]);
            total := total + Val(strings[i]);
            //total := total + ToNumber(numdesc[1]);
      //  );
    );
    
    total;