Javascript VS PHP rounding

后端 未结 6 729
轮回少年
轮回少年 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条回答
  •  太阳男子
    2020-12-18 05:18

    I was thinking a bit on this, and wanted to share my solution, let it not go to waste:

    function roundNumber(number, decimals) {      
        var d = parseInt(decimals,10),
            dx = Math.pow(10,d),
            n = parseFloat(number),
            f = Math.round(Math.round(n * dx * 10) / 10) / dx;
        return f.toFixed(d);
    }
    

    This does not use string functions, or any forced up or down rounding.

    Test it here: http://jsfiddle.net/inti/hMrsp/4/

    Edit: corrected, was cutting down zeros at the end

提交回复
热议问题