在javascript中只允许小数点后两位数

Vai*_*ain 3 .net javascript

我有一个变量 i=28.57142857142857; 我想提醒(i);在用户屏幕上提醒此变量。但我只想要小数点后两位数。即28.57

怎么做。

Koo*_*Inc 5

尝试使用 toFixed:

 alert(i.toFixed(2));
Run Code Online (Sandbox Code Playgroud)

如果您需要Jappie的下一个答案中提到的精度,您可以像这样覆盖本机 toFixed 方法:

Number.prototype.toFixed = function (precision) {
 var power = Math.pow(10, precision || 0);
 return String(Math.round(this * power) / power);
};
Run Code Online (Sandbox Code Playgroud)