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?