Skip to content Skip to sidebar Skip to footer

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

Solution 1:

This isn't anything to do with rounding per se, but is to do with how decimal numbers are represented in binary-based hardware.

Check out the floating point guide for lots more information on this, as well as solutions/alternatives.

Solution 2:

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

Here is an example

functionroundNumber(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 .X99999999999returnparseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))     
}


var val = 43.65 * 2.5;
    val+= val*0.40console.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));

Solution 3:

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

functionroundNumber(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

Solution 4:

php rounds to 152.78, because it sees 152.77499 which is 152.775 and in the end 152.178. can't you use rounded value from php?

Solution 5:

It is because the different precisions used in JS (by the browser) and PHP or actually how many bits are used to store the numbers.

you can make your JS rounding function do this to round to the 2nd digit Math.round(floatNumber*100)/100

Post a Comment for "Javascript Vs Php Rounding"