我在jsp中有以下几句语句:
1<script language="javascript">
2x=a/b;
3
4</script>
现在所得x的精度很高我想问一下怎么样才能使它转化为精度为1.00这样的数值或字符串都有行.
注意:是在客户端脚本,不是服务端脚本!
---------------------------------------------------------------
Number.toFixed(fracDigits) fracDigits为小数点后的位数,只在IE5.5以上可行
IE5.5以下我用的是s=Number.toString(); s=s.substr(0,s.indexOf('.')+fracDigits);
---------------------------------------------------------------
用VBScript来处理最方便.
1<script language="VBScript">
2x=a/b;
3MsgBox(FormatNumber(x,2))
4</script>
---------------------------------------------------------------
1<script>
2String.prototype.fn = function(n)
3{ s=""
4for(i=0;i<n;i++)s+=this
5return s
6}
7Number.prototype.fix = function(num)
8{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));
9}
10alert((5.31-1.31).fix(2));
11</script>
上边的代码返回任意数的保留n位小数值,为了考虑货币的效果(xx.xx)形势,所以长了一点儿,因为4.00的格式是不能显示的(以数字方式),如果不用顾及那个用下边的就行
1<script>
2Number.prototype.fix = function(num)
3{with(Math)return round(this.valueOf()*pow(10,num))/pow(10,num);
4}
5alert((5.31-1.31).fix(2));
6</script>
---------------------------------------------------------------
1<script>
2function Number.prototype.Fixed(num){
3with(Math){
4var m=pow(10,Number(num))
5return round(this*m)/m;
6}
7}
8alert((2/3).Fixed(2))
9alert((2/3).toFixed(2));//ie5.5+
10</script>
---------------------------------------------------------------
通用的toFixed
1<script>
2try {
3Number.toFixed();
4}
5catch(e) {
6function Number.prototype.toFixed(dot) {
7with(Math){
8var m=pow(10,Number(dot))
9var s = (round(this*m)/m).toString();
10}
11if(s.indexOf('.') < 0)
12s += ".";
13s += "000000000000";
14return s.substr(0,s.indexOf('.')+dot+1);
15}
16}
17
18alert((2/3).toFixed(2));
19
20</script>