3

In this example/behaviour is something very strange.

Why does the function toFixed for the first two examples work and for this last one not?

    //example 1
    var num = 554.956;
    var n = num.toFixed(2)
    console.log(n);
    var num2 = 554.955;
    var n2 = num2.toFixed(2)
    console.log(n2);

    //output 554.96 and 554.96

    //example 2        
    var num5 = 5.956;
    var n5 = num5.toFixed(2)
    console.log(n5);
    var num6 = 5.955;
    var n6 = num6.toFixed(2)
    console.log(n6);

    //output 5.96 and 5.96
    
    //example 3
    var num3 = 55.956;
    var n3 = num3.toFixed(2)
    console.log(n3);
    var num4 = 55.955;
    var n4 = num4.toFixed(2)
    console.log(n4);
    
    //output 55.96 and 55.95

Related to: php round vs javascript toFixed

EDIT: about the duplicates especially this one: toFixed function not working properly ( please give a reason not an alternative)

The answer is very good and helps me to understand the difference between x.955 and x.956, but doesn't answer why this happens only to the 55.955 in my example and not to the 5.955 or 554.955.

Community
  • 1
  • 1
Edwin
  • 2,146
  • 20
  • 26
  • 2
    What would you expect to behave differently? – ssc-hrep3 May 05 '17 at 11:21
  • 1
    Please do search in stackoverflow before posting ... checkout this http://stackoverflow.com/questions/29008083/tofixed-function-not-working-properly-please-give-a-reason-not-an-alternative – Biby Augustine May 05 '17 at 11:21
  • the answer to last example to be `55.96` and `55.96` – Edwin May 05 '17 at 11:22
  • this two duplicates just tell me about rounding or why is a string etc.. the best close answer is the duplicate from @BibyAugustine, but that as well is not satisfying completely my question, because in all examples I use the same decimal values ( xxx.955 and xxx.956) – Edwin May 05 '17 at 11:35
  • You actually don't say much more than "does not work" so I'm not fully sure of what your doubt is but... It's [by design](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed): *«The number is rounded if necessary»*. The rationale is that most of the times you want to minimize precision loss. – Álvaro González May 05 '17 at 11:51
  • @Edwin It's not about the decimal part, it's about the whole number. Check the duplicate about floating point representation. Basically, `.554955e3`, `.55955e2` and `.5955e1` are *very* different numbers (using the same principle on decimal numbers, not binary ones) – Bergi May 05 '17 at 12:37

0 Answers0