Question about using the javascript function toFixed ()

advertisements

I was looking for a JavaScript function to round a number to a specified amount of decimal places & I found this page: http://www.kadimi.com/en/round-float-349

That page includes a section that uses prototyping & the toFixed() function..... however I also found this page: http://freewebdesigntutorials.com/javaScriptTutorials/jsNumberObject/toFixedMethod.htm (see last example) & this uses the toFixed function straight up & appears to do the same thing.

I'm not a big javascript person so apologies if this is a stupid question, but what's the difference between them?

Here they are for clarity..

With prototype:

if (!Number.toFixed) {
  Number.prototype.toFixed=function(n){
    return Math.round(this*Math.pow(10, n)) / Math.pow(10, n);
  }
}

// example:
floating_number = 123.45687;
decimal_points = 2;
window.alert(floating_number.toFixed(decimal_points));

Standard:

var numex = 3.1415926535;
alert( numex.toFixed(5) );

I also tried out that first batch of code with this function..

function round_float(number,places){
    if (!number.toFixed) {
        number.prototype.toFixed=function(places){
            return Math.round(this*Math.pow(10, places)) / Math.pow(10, places);
        }
    } else {
        alert('bad');
    }
}

It went into the "bad" alert section..... I'm guessing that was caused by the false response by toFixed; any idea why this function is written like that then?


I'm not sure why you have the alert('bad') in your else block; all that really happens in the "bad" case, is that the number variable already has a member called toFixed defined (which evaluates to true when coerced to a boolean - always the case for a function).

That's not necessarily a bad thing, since this is what you want the end result to be?! The code seems to be defining a version if toFixed if there isn't already a native* implementation. The alert fires when there is native* support.

*(Well, either native to the browser or already added to the prototype by a JS library. Either way, it's already there so no more work is needed.)