Pjn2020 Pjn2020 - 2 months ago 15
Javascript Question

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

Answer

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

That said, I just wrote this. Perhaps it is what you want?

function roundNumber(number, decimals) {
  decimals = parseInt(decimals,10);
  var dec = Math.pow(10,decimals)
  number=""+Math.ceil(parseFloat(number)*dec); // notice the ceil to round up 
  return parseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))     
}

Or Math.round is what you wanted after all:

http://jsfiddle.net/mplungjan/TDMds/

function roundNumber(number, decimals) {
  decimals = parseInt(decimals,10);
  var dec = Math.pow(10,decimals)
  number=""+Math.round(parseFloat(number)*dec); // notice the ceil to round up 
  return parseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))     
}

Result:

152.775 ~= 152.78? --> 152.78
 15.803 ~=  15.80? -->  15.80
 15.805 ~=  15.81? -->  15.81 
 14.803 ~=  14.80? -->  14.80