[removed] Comparing two float values

前端 未结 4 1790
忘了有多久
忘了有多久 2020-12-09 01:55

I have this JavaScript function:

Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {

    var cv = parseFloat(cfVal).toFixed(2);
    var av = parse         


        
4条回答
  •  失恋的感觉
    2020-12-09 02:33

    The Math.fround() function returns the nearest 32-bit single precision float representation of a Number.

    And therefore is one of the best choices to compare 2 floats.

    if (Math.fround(1.5) < Math.fround(1.6)) {
        console.log('yes')
    } else {
        console.log('no')
    }
    
    >>> yes
    
    // More examples:
    console.log(Math.fround(0.9) < Math.fround(1));                            >>> true
    console.log(Math.fround(1.5) < Math.fround(1.6));                          >>> true
    console.log(Math.fround(0.005) < Math.fround(0.00006));                    >>> false
    console.log(Math.fround(0.00000000009) < Math.fround(0.0000000000000009)); >>> false
    

提交回复
热议问题