Extracting a number from a line that represents a negative value

i have a text document that is columnar in nature. one of the columns is up to 7 characters, with the 7th character if present being the dash “-” to represent a negative number. right now i am extracting the 7th character and testing if a “-” and if so then forcing the preceding 6 characters to be negative with this brute force logic:

            endinv  = line.substr(106,6).trim();
            // check last column of endinv for "-" inv decrease 
            if (line.substr(112,1) == '-') {
               endinv *= -1;
            }

is there a better way?

The approach isn’t so bad, pulling the characters out like that. My biggest concern are the numbers passed into substr. What is 106? What is 112? Would some change in the document break those hardcoded numbers? Would it be better to have them as variables to better account for that?

            const dataLen = 6;
            const modifierLen = 1;
            const dataStart = 106; // but why 106?
            endinv = line.substr(dataStart, dataLen).trim();

            // check last column of endinv for "-" inv decrease
            const modifierStart = dataStart + dataLen;
            if (line.substr(modifierStart, modifierLen) == '-') {
               endinv *= -1;
            }

I don’t have a concrete suggestion for this thread; but my initial reaction was along the lines of: you should create a grammar for the format you hope to parse. Number literals should be parsed within a context where you expect numbers; most other strategies lead to odd failure scenarios.

Thanks for the responses. I will try both approaches. My primary goal is a simple script as this is an embedded implementation of JS within a large CM application and the users/owners of the document/scripts are primarily end users with some GUI experience for document design but little actual coding.

again thanks

1 Like