to: fason(阿信),什么叫想当然?
顶楼的又没有说要保留小数!我当然给他返回一个整数了!
想要保留小数也可以啊
toFixed(n)不就可以?不过对浏览器有版本要求而已
像没有版本要求就自己写!
比如:
<script>
String.prototype.fn = function(n)
{ s=""
for(i=0;i<n;i++)s+=this
return s
}
Number.prototype.fix = function(num)
{with(Math)return (round(this.valueOf()*pow(10,num))/pow(10,num)).toString().search(/\./i)==-1?(round(this.valueOf()*pow(10,num))/pow(10,num)).toString()+"."+"0".fn(num):(round(this.valueOf()*pow(10,num))/pow(10,num));
}
alert((5.31-1.31).fix(2));
</script>
上边的代码返回任意数的保留n位小数值,为了考虑货币的效果(xx.xx)形势,所以长了一点儿,因为4.00的格式是不能显示的(以数字方式),如果不用顾及那个用下边的就行
<script>
Number.prototype.fix = function(num)
{with(Math)return (round(this.valueOf()*pow(10,num))/pow(10,num)).toString().search(/\./i)==-1?parseFloat((round(this.valueOf()*pow(10,num))/pow(10,num)).toString()+"."):(round(this.valueOf()*pow(10,num))/pow(10,num));
}
alert((5.31-1.31).fix(2));
</script>
顶楼的又没有说要保留小数!我当然给他返回一个整数了!
想要保留小数也可以啊
toFixed(n)不就可以?不过对浏览器有版本要求而已
像没有版本要求就自己写!
比如:
<script>
String.prototype.fn = function(n)
{ s=""
for(i=0;i<n;i++)s+=this
return s
}
Number.prototype.fix = function(num)
{with(Math)return (round(this.valueOf()*pow(10,num))/pow(10,num)).toString().search(/\./i)==-1?(round(this.valueOf()*pow(10,num))/pow(10,num)).toString()+"."+"0".fn(num):(round(this.valueOf()*pow(10,num))/pow(10,num));
}
alert((5.31-1.31).fix(2));
</script>
上边的代码返回任意数的保留n位小数值,为了考虑货币的效果(xx.xx)形势,所以长了一点儿,因为4.00的格式是不能显示的(以数字方式),如果不用顾及那个用下边的就行
<script>
Number.prototype.fix = function(num)
{with(Math)return (round(this.valueOf()*pow(10,num))/pow(10,num)).toString().search(/\./i)==-1?parseFloat((round(this.valueOf()*pow(10,num))/pow(10,num)).toString()+"."):(round(this.valueOf()*pow(10,num))/pow(10,num));
}
alert((5.31-1.31).fix(2));
</script>
<script>
Number.prototype.fix = function(num)
{with(Math)return round(this.valueOf()*pow(10,num))/pow(10,num);
}
alert((5.31-1.31).fix(2));
</script>
<script>
function Number.prototype.Fixed(num){
with(Math){
var m=pow(10,Number(num))
return round(this*m)/m;
}
}
alert(c(56.10,23.12).Fixed(2));
function c(n1,n2){
var m=0,s1=n1.toString(),s2=n2.toString();
m=s1.split(".")[1].length
m=s2.split(".")[1].length
return (n1-n2).Fixed(m)//高版本可以用(n1-n2).toFixed(m)
}
</script>
<script>
function qswhSub(n1,n2){
var m1=0,m2=0,m;
try{m1=n1.toString().split(".")[1].length}catch(e){}
try{m2=n2.toString().split(".")[1].length}catch(e){}
m=Math.pow(10,Math.max(m1,m2));
return ((n1*m)-(n2*m))/m
}
alert(qswhSub(5.3,1.31))
alert(qswhSub(5.31,1.31))
</script>或者用以前的版本qswhAdd,只是第二个参数要加负号