1

I have one php function and having

phpans = round(53.955,2)

and javascript function

var num  = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);

both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening .. Thanks is Advance

cweiske
  • 30,033
  • 14
  • 133
  • 194
Rajat Gupta
  • 342
  • 2
  • 12

2 Answers2

4

Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.

var start = 53.955,
        res1,
        res2;
    
    res1 = start.toFixed(2);
    res2 = (start * 100).toFixed(0) / 100;
    console.log(res1, res2);
//Outputs
"53.95"
53.96
Edwin
  • 2,146
  • 20
  • 26
Styphon
  • 10,304
  • 9
  • 52
  • 86
0

JAvascript toFixed: The toFixed() method converts a number into a string, keeping a specified number of decimals.

php round: Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.

Javascript function :

function round_up (val, precision) {
    power = Math.pow (10, precision);
    poweredVal = Math.ceil (val * power);
    result = poweredVal / power;

    return result;
}
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33
  • Ohk @ahmed . I understand but it is giving wrong value in some special cases ...Thanks for Help... – Rajat Gupta May 05 '17 at 10:57
  • Thanks @ahmed for this code ...but it not properly working for 55.951 if third digit is greater than or equal to 5 then should be round otherwise 2 digit will show as same – Rajat Gupta May 05 '17 at 11:08