0

I have 2 big variables, and I need to compare like:

var a =  15000000000000000000000001  // integer
var b = "15000000000000000000000000" // string

In all my test comparisons get wrong results. eg:

  1. Convert var b into a integer

    var a = 15000000000000000000000001
    var b = 15000000000000000000000000
    a > b // return false and is wrong
    
  2. Convert var a into a string

    var a = "1500000000000000000000001"
    var b = "15000000000000000000000000"
    a > b // return true and is wrong
    

My solution:

function compareCheck(a,b){
    if (a.length > b.length) {
        return true;
    }
    else if (a.length == b.length) {
        if (a.localeCompare(b) > 0) {
            return true
        }
        else return false;
    }
    else return false;
}

var a = "15000000000000000000000001"
var b = "15000000000000000000000000"

compareCheck(a,b) // return true and is correct

var a = "1500000000000000000000001"
var b = "15000000000000000000000000"

compareCheck(a,b) // return false and is correct

My question is whether the solution found is the correct one, or will have problems in the future?

  • Sorry for not being constructive, but isn't this is the sort of problem that results from a language like Javascript with its "yeah, whatever" approach to datatypes!!! – bazza Jun 27 '13 at 05:55
  • It depends on what you want to get for `00000001 > 900` – perreal Jun 27 '13 at 05:58
  • my variables never begin with 0. Basically they are numbers, but as long as javascript has problems with large numbers, we have to convert them to strings. – Anuta Wascar Jun 27 '13 at 06:13

1 Answers1

1

Here the standard practice I believe is to subtract one number from another and compare it with an epsilon value.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • That makes sense for one of the cases, comparing two ints. But OP's solution shows that for the case of two strings, he wants the one with the longest length, but if they're the same, compare something else? – damienc88 Jun 27 '13 at 05:46