javascripttofixed

How to display second zero when only single digit is returned after decimal, in JavaScript?


I have two functions here...

function getCostOne() {
  var cost = 1.5;  
  return 1 * cost.toFixed(2);
}

and...

function getCostTwo() {
  var cost = 1.5;  
  return 1 + cost.toFixed(2);
}

What is the difference between multiplying cost.toFixed(2) and adding cost.toFixed(2)?

Why does multiplying it return .5 and adding return .50?


Solution

  • Those functions return 1.5 and "11.50" respectively. Working JSBin Demo...

    console.log(1 * '1.50');
    console.log(1 + '1.50');
    

    It looks like the string is cast in the first case (as though you had called parseFloat('1.50') and then concatted in the second. However, this is only the results on my own browser. Take a look at the official MDN Web Docs...

    console.log('foo' * 2);
    // expected output: NaN
    

    So, Chrome is probably handling it well, but I wouldn't expect that kind of behavior across all browsers!

    If you want them to both definitely return the right numbers, do all the mathematical logic first, and then format it with toFixed(). That code would look like...

    function getCostTwo() {
      var cost = 1.5;
      cost += 1;     // do the math logic FIRST!
      return cost.toFixed(2);   // once the number is just right, we format it!
    }