我正在寻找一个 JavaScript 函数来将数字四舍五入到指定的小数位数,我找到了这个页面:http://www.kadimi.com/en/round-float-349
该页面包括一个使用原型(prototype)设计和 toFixed() 函数的部分......但是我也找到了这个页面:http://freewebdesigntutorials.com/javaScriptTutorials/jsNumberObject/toFixedMethod.htm(见最后一个例子)并且它直接使用了 toFixed 函数并且看起来做同样的事情.
我不是一个大 javascript 人,如果这是一个愚蠢的问题,我深表歉意,但它们之间有什么区别?
这里是为了清楚起见..
有原型(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));
标准:
var numex = 3.1415926535;
alert( numex.toFixed(5) );
我也用这个函数尝试了第一批代码..
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');
}
}
它进入了“错误”警报部分.....我猜这是由 toFixed 的错误响应引起的;知道为什么要这样写这个函数吗?
最佳答案
简单。并非所有浏览器都有 toFixed
,因此在第一个示例中它提供了一个安全网。替代方案意味着浏览器确实有一个 toFixed
,它不是“坏的”而是“正常的”。
关于javascript - 关于javascript的toFixed()函数用法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5300742/