Javascript VS PHP rounding

后端 未结 6 732
轮回少年
轮回少年 2020-12-18 05:11

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



        
6条回答
  •  旧时难觅i
    2020-12-18 05:27

    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));

提交回复
热议问题