2

I have a string like so:

(999.08) - (1025.67)

I need to be able to find the range between these two values as a floting point even if they are negative values so (-999.08) - (-1025.67) would also be in scope.

Assume i would need to use a regex and join the two in some sort of array?

1
  • 1
    it seems you have to create array using 'for' loop only. Can't imagine other solution. Commented Oct 19, 2010 at 13:51

6 Answers 6

3

From looking over everyone else's answers, I can't tell if any of them deal with negative numbers properly. I'll throw this in the ring in case anyone needs it.

function parse(str) {

    // init to NaN
    var result = Number.NaN;

    // capture numbers in groups
    var pat = new RegExp(/\((-?\d+.?\d*)\)\s*-\s*\((-?\d+.?\d*)\)/);
    var match = str.match(pat);

    if (match) {
        // match[0] is whole match which is not useful
        var a = new Number(match[1]); // 1st group is 1st number
        var b = new Number(match[2]); // 2nd group is 2nd number
        result = Math.abs(a - b);
    }

    return result;
}

demo: http://jsbin.com/oseba4/edit

Sign up to request clarification or add additional context in comments.

4 Comments

Hi. I was just about to ask as this line of code: var floatVal = s.replace(/(|)|\s*/g, "").split("-"); splits on a negative number.
@RyanP13 if the string parsing fails, then won't be able to get a valid range value back. you can use isNaN() on the return value to see if it worked correctly.
I don't suppose you could use Number.NaN instead of the comment and the ridiculously confusing parseInt('z').
@ChaosPandion yes, that would be better. I somehow have gotten to this point without knowing about that reference.
2

You can split the string on the " - " using .split, use replace to remove the brackets, and then parseFloat the two numbers. After that, check for the highest of the two numbers, and subtract for the range.

Comments

2

There are a couple of ways: Here is one: sort of the long way around

var myString = "(999.08) - (1025.67)"

var myFloatValues = mystring.split("-");

myFloatValues[0] = myFloatValues[0].replace("(", "").replace(")", "");
myFloatValues[1] = myFloatValues[1].replace("(", "").replace(")", "");

myFloatValues[0] = parseFloat(myFloatValues[0])
myFloatValues[1] = parseFloat(myFloatValues[1])

Here is using a regex:

var myString = "(999.08) - (1025.67)"
var myFloatValues = (myString.replace(/\(*|\)*|\s*/g, "")).split("-");
myFloatValues[0] = parseFloat(myFloatValues[0])
myFloatValues[1] = parseFloat(myFloatValues[1])

Note: a useful site I have been using for a ling time

This site helps a person generate valid regular Expressions. Give it a try http://www.jslab.dk/tools.regex.php

4 Comments

thanks that's really helpful. Am still strugling with Regex :(
Works now, but the regex leaves the terminating bracket in place. (aren't regexes awesome?)
I know the regEX leave terminating brackets but parseFloat will ignore unusual characters at the end. Example parseFloat("123.00abc") will result in "123.00"
Yeah... I program with serious OCD... :)
2

in addition to John hartsocks answer: add a check after you set the float values to swap around the values if the first value is bigger than the second

function Check(myValue,myString)
{
    var myFloatValues = (mystring.replace(/\(*|\)*|\s*/g, "")).split("-");
    myFloatValues[0] = parseFloat(myFloatValues[0]);
    myFloatValues[1] = parseFloat(myFloatValues[1]);
    if (myFloatValues[0] > myFloatValues[1]) // swap
    {
        var temp = myFloatValues[0];
        myFloatValues[0] = myFloatValues[1];
        myFloatValues[1] = temp;
    }
    if (myFloatValues[0] < myValue && myFloatValues[1] > myValue) // this will be a problem if you dont swap them
        return true;
    return false;
}

Comments

1

Pesuo code:

// Our variables
float num1;
float num2;
string myString = "(999.08) - (1025.67)";

// Split the data string on - character
arrParts[] = myString.split("-");

// Loop through each resulting split
for int i = 0; i < arrParts.Count; i++)
{
   // Trim result to remove whitespace
   arrParts[i] = arrParts[i].trim();

   // Take all the characters in string except first and last
   arrParts[i] = arrParts[i].substring(1, part.length-2);
}

// Cast out numbers
num1 = (float)arrParts[0];
num2 = (float)arrParts[1];

Solution assumptions

Assumes input string is correct format, and that no fewer or more than 2 valid float numbers will be provided.

For range calculation:

Two ways, either subtract either from either and get absolute value to determine range, or take the lengthier method of guaranteeing smaller number is taken for bigger

Notes on regexp

I would argue against using regexp where possible (although this is very subjective) because it can turn reviewing this code in the future into a difficult task.

If you do use regexp make sure you comment in the expected input formats to protect against this.

Comments

1

This is where eval* shows its true power.

range = Math.abs(eval(string));

*No, it's NOT evil ;)

1 Comment

I thought we tossed that curse into the fires of mount doom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.