phpjavascript

Javascript VS PHP rounding


I am having some problems with the way PHP and javascript round numbers. I am using PHP's round function and this javascript function:

function roundNumber(number, decimals) {     
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    var value = parseFloat(newnumber);
    return value;
}

The number i am trying to round is 43.65 * 2.5 + 40% which when done using a calculator = 152.775 or when rounded in PHP = 152.78.

In javascript when i do a console.log the number is 152.774999999998 and when rounded with the above function gives me 152.77

Any help to reslove this issue is greatly appreciated


Solution

  • Please have a look at How to deal with floating point number precision in JavaScript?

    Here is an example

    function roundNumber(number, decimals) {
      decimals = parseInt(decimals,10);
      var dec = Math.pow(10,decimals)
      console.log(dec,parseFloat(number)*dec);
      number=""+Math.round(parseFloat(number)*dec+.0000000000001); // fixed the .X99999999999
      return parseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))     
    }
    
    
    var val = 43.65 * 2.5;
        val+= val*0.40
    
    console.log(val+' ~= 152.78? --> '+roundNumber(val,2).toFixed(2));
    console.log('15.803 ~= 15.80? --> '+roundNumber(15.803,2).toFixed(2));
    console.log('15.805 ~= 15.81? --> '+roundNumber(15.805,2).toFixed(2));
    console.log('14.803 ~= 14.80? --> '+roundNumber(14.803,2).toFixed(2));
    console.log('0.575 ~=  0.58? --> '+roundNumber(0.575,2).toFixed(2));