Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript VS PHP rounding

Tags:

javascript

php

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

like image 246
Pjn2020 Avatar asked Jun 22 '11 08:06

Pjn2020


1 Answers

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.

like image 101
Andrzej Doyle Avatar answered Oct 05 '22 23:10

Andrzej Doyle