见代码
<
script
>
Number.prototype.round = function (){
var b = arguments.length > 0 ? arguments[ 0 ] : 0 ;
var NUMBER = Math.round( this * Math.pow( 10 , b)) * Math.pow( 10 , - b);
NUMBER = Math.round(NUMBER * 100000000000 ) / 100000000000 ;
var ret = NUMBER.toString();
if (b > 0 ){
if (ret.indexOf( " . " ) <= - 1 ){ret = ret.space(b, " 0 " , true );}
else {
if (ret.split( " . " )[ 1 ].length <= b){ret = ret.space((b - ret.split( " . " )[ 1 ].length), " 0 " );}
else {ret = ret.split( " . " )[ 0 ] + " . " + ret.split( " . " )[ 1 ].substr( 0 , (b - 1 ));}
}
}
if (b <= 0 ) ret = ret.split( " . " )[ 0 ]
return ret;
}
String.prototype.space = function (n){
var s, d;
switch (arguments.length){
case 1 : s = " " ; d = "" ; break ;
case 2 : s = arguments[ 1 ]; d = "" ; break ;
case 3 : s = arguments[ 1 ]; d = eval(arguments[ 2 ]) ? " . " : "" ;
}
var ret = this + d;
for ( var i = 0 ; i < n; i ++ ){
ret += s;
}
return ret;
}
var a = 336813.56 + 84651.6 ;
alert(a);
alert(a.round( 2 ));
</ script >
Number.prototype.round = function (){
var b = arguments.length > 0 ? arguments[ 0 ] : 0 ;
var NUMBER = Math.round( this * Math.pow( 10 , b)) * Math.pow( 10 , - b);
NUMBER = Math.round(NUMBER * 100000000000 ) / 100000000000 ;
var ret = NUMBER.toString();
if (b > 0 ){
if (ret.indexOf( " . " ) <= - 1 ){ret = ret.space(b, " 0 " , true );}
else {
if (ret.split( " . " )[ 1 ].length <= b){ret = ret.space((b - ret.split( " . " )[ 1 ].length), " 0 " );}
else {ret = ret.split( " . " )[ 0 ] + " . " + ret.split( " . " )[ 1 ].substr( 0 , (b - 1 ));}
}
}
if (b <= 0 ) ret = ret.split( " . " )[ 0 ]
return ret;
}
String.prototype.space = function (n){
var s, d;
switch (arguments.length){
case 1 : s = " " ; d = "" ; break ;
case 2 : s = arguments[ 1 ]; d = "" ; break ;
case 3 : s = arguments[ 1 ]; d = eval(arguments[ 2 ]) ? " . " : "" ;
}
var ret = this + d;
for ( var i = 0 ; i < n; i ++ ){
ret += s;
}
return ret;
}
var a = 336813.56 + 84651.6 ;
alert(a);
alert(a.round( 2 ));
</ script >
js浮点数字计算的问题一直让我很头疼,长考之后想出这样一个解决办法。目前在我的系统中运行正常,是否具有普遍性,还请各位读者代为测试一下。结果如何,请大家回复。
Number.prototype.round还具有一些其它特性,大家可以试试alert(a.round(3))和alert(a.round(-2))。