开发者

Compare two floats in JavaScript

How can I compare two floats in JavaScript? Or perhaps a float and an int.

if (5 > 4.3.3)

if (5.0 > 5.3)

Thankful for all input!

Update

I need to for an iPhone app that I am developing in Appcelerator. I need to compare iOS versions and display different content to each. So if a device is running 5.0 and another is running 4.3.3 I开发者_C百科 need to know the difference in my code.


Just like that.

if (5.0 > 5.3)

In your 1st example you do not have a valid number [4.3.3].


You may use something along the lines of http://maymay.net/blog/2008/06/15/ridiculously-simple-javascript-version-string-to-object-parser/

Basically he uses:

function parseVersionString (str) {
    if (typeof(str) != 'string') { return false; }
    var x = str.split('.');
    // parse from string or default to 0 if can't parse
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var pat = parseInt(x[2]) || 0;
    return {
        major: maj,
        minor: min,
        patch: pat
    }
}


Basic comparator can look like:

  1. Convert to correct positional structure
  2. Compare lengths
  3. Compare values

function compareVer(a, b, sep = '.') {
  // 1. Convert to correct positional structure
  const aP = a.split(sep);
  const bP = b.split(sep);
  // 2. Compare lengths 
  if (aP.length > bP) return 1;
  if (bP.length > aP) return -1;
  for (let i = 0; i < aP.length; ++i) {
    // 3. Compare values
    // You can add necessary type conversions 
    // Ex.: add parseInt, if you want to support `001=1` and not `3f=3f`
    if (aP[i] > bP[i]) return 1;
    if (bP[i] > aP[i]) return -1;
  }
  return 0;
}


console.log(compareVer('5', '4.3.3'));      //  1  gt
console.log(compareVer('5.0.2', '5.0.2'));  //  0  eq
console.log(compareVer('5.0', '5.3'));      // -1  lt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜