User
User

Reputation: 145

Integer Comparison

I need to compare two Integers which could exceed Integer range limit. How do I get this in javascript. Initially, I get the value as String, do a parseInt and compare them.

var test = document.getElementById("test").value;
var actual = document.getElementById("actual").value;
if ( parseInt(test) == parseInt(actual)){
  return false;  
}

Any options to use long ? Also, which is best to use parseInt or valueOf ??

Any suggestions appreciated,

Thanks

Upvotes: 6

Views: 45825

Answers (3)

jfriend00
jfriend00

Reputation: 707158

Assuming integers and that you've already validated for non-numeric characters that you don't want to be part of the comparison, you can clean up some leading/trailing stuff and then just compare lengths and if lengths are equal, then do a plain ascii comparison and this will work for any arbitrary length of number:

function mTrim(val) {
    var temp = val.replace(/^[\s0]+/, "").replace(/\s+$/, "");
    if (!temp) {
        temp = "0";
    }
    return(temp);
}

var test = mTrim(document.getElementById("test").value);
var actual = mTrim(document.getElementById("actual").value);

if (test.length > actual.length) {
    // test is greater than actual
} else if (test.length < actual.length) {
    // test is less than actual
} else {
    // do a plain ascii comparison of test and actual
    if (test == actual) {
        // values are the same
    } else if (test > ascii) {
        // test is greater than actual
    } else {
        // test is less than actual
    }
}

Upvotes: 1

nhahtdh
nhahtdh

Reputation: 56809

Leave them in String and compare (after you have cleaned up the string of leading and trailing spaces, and other characters that you consider safe to remove without changing the meaning of the number).

The numbers in Javascript can go up to 53-bit precision. Check whether your number is within range.

Since the input is expected to be integer, you can be strict and only allow the input to only match the regex:

/\s*0*([1-9]\d*|0)\s*/

(Arbitrary leading spaces, arbitrary number of leading 0's, sequence of meaningful digits or single 0, arbitrary trailing spaces)

The number can be extract from the first capturing group.

Upvotes: 4

xdazz
xdazz

Reputation: 160833

You'd better to assign the radix. Ex. parseInt('08') will give 0 not 8.

if (parseInt(test, 10) === parseInt(actual, 10)) {

Upvotes: 4

Related Questions