J. Laderoute J. Laderoute - 4 years ago 168
Javascript Question

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download