0

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);
FranXh
  • 4,481
  • 20
  • 59
  • 78
  • Well if you immediately convert the return value of `.toFixed()` back to a number, you risk re-introducing the floating point inaccuracy phenomena that you're trying to eliminate. `.toFixed()` returns a **string**. – Pointy Aug 16 '14 at 14:45
  • Could you give me an example please? – FranXh Aug 16 '14 at 14:48
  • It (probably) won't be a problem if you don't use "numb" in any subsequent math, but the issue is that arithmetic operations can introduce slight inaccuracies. Your application may be OK; it's just a thing to keep in mind. – Pointy Aug 16 '14 at 14:57

2 Answers2

1

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.

Community
  • 1
  • 1
jayelm
  • 7,236
  • 5
  • 43
  • 61
1

Applause to this reference source, ToFixed() doesn't handle corner cases very well.

const value = 1.005;

console.log(value.toFixed(2)) // expect 1.01, return 1.00
iyhc
  • 134
  • 3