J. Laderoute
J. Laderoute

Reputation: 313

fnumber.toFixed(2) does not always truncate the value to two decimal points

What can be done to prevent numbers like this appearing in my output?

Here is my javascript code.

$("#TaskListing table tr td#Begin input").each(function (index, element) {           
  var theRow = $(element).parent().parent();
  var thePercent = $(theRow).children("tr td#Percent:first");
  currentvalue = $(theRow).data("millisecs");
  fnumber = currentvalue / totalTimeMs;
  thePercent.text( 100 * fnumber.toFixed(2));
});

I thought that using fnumber.toFixed(2) would prevent values like this (28.0000000000004 ) from appearing but yet they appear from time to time.

enter image description here

Upvotes: 0

Views: 157

Answers (2)

Web Dev Guy
Web Dev Guy

Reputation: 1789

Change your code to use toFixed like this.

thePercent.text( (100 * fnumber).toFixed(2) );

You want to perform the calculation first then send it to the toFixed() method

Upvotes: 1

J. Laderoute
J. Laderoute

Reputation: 313

The answer is to use thePercent.text( (100 * fnumber).toFixed(2) );

Not sure what the issue is with the other way of doing it, maybe it's a problem with .toFixed() for values that can't be expressed without using a repeating fraction.

Upvotes: 0

Related Questions