javascriptfloating-pointnumbersfloating-accuracyfloating-point-precision

JavaScript: Downsides of toFixed(...) method


In my programs, I need "float" numbers rounded to the nearest two decimal digits, and after some research I decided to use toFixed(..) for this purpose, like shown in the example below. What are the downsides of using toFixed()? Does it work in all browsers correctly? If not, what are some cases that it does not work correctly?

var numb = 123.23454; 
numb = +numb.toFixed(2);

Solution

  • Provided the fixed decimal point behavior is satisfactory, there's nothing wrong with using toFixed. According to Mozilla's Developer Documentation, this method was implemented in JavaScript 1.5, which was released in 2000, so you'll see compatibility with virtually every modern browser, including IE6+.

    edit: Ah, and if you weren't aware, toFixed turns a number into a string, useful for doing, well, String things. If that was not your intended behavior, look here for an SO question on the Math.round method.