How to round in javascript like PHP do
You can use toPrecision Function
It will rounded by the precision
provided. Here I rounded by 4
to get 6.405
and then rounded by 3
to get 6.41
parseFloat((6.404999999999999).toPrecision(4)).toPrecision(3);
console.log(parseFloat((6.404999999999999).toPrecision(4)).toPrecision(3));
I think the best answer is the next:
function roundLikePHP(num, dec){
var num_sign = num >= 0 ? 1 : -1;
return parseFloat((Math.round((num * Math.pow(10, dec)) + (num_sign * 0.0001)) / Math.pow(10, dec)).toFixed(dec));
}
I tried the other solutions with 1.015
and doesn't work as expected.
This solution works well, like PHP round, with all the numbers I tried.