JavaScript中实现四舍五入后保留小数的方法

2015-03-26 15:48:36

在JavaScript中没有四舍五入后保留小数的方法,试试以下方法是可以的

1、round和pow结合

Math.round(num*Math.pow(10,n))/Math.power(10,n)

如:

var num=2011.1234
var count1=Math.round(num*Math.pow(10,1))/Math.pow(10,1);//保留一位小数,结果为2011.1
var count2=Math.round(num*Math.pow(10,3))/Math.pow(10,3);//保留三位小数结果为2011.123

//上述代码化简为:

var count1=Math.round(num*10)/10;//保留一位小数,结果为2011.1

var count3=Math.round(num*1000)/1000;//保留一位小数,结果为2011.123

  化简之后可以看出,如果保留1位小数,将该数值放大10倍,再缩小10倍;如果保留两位小数则放大100倍,再缩小100倍,以此类推。

2、toFixed函数和toPrecision函数

  toFixed(x):返回某数四舍五入之后保留x位小数

  toPrecision(x):返回某数四舍五入之后保留x位字符

  使用格式:

  数字.toFixed(x)  //保留n位小数

  数字.toPrecision(x)  //保留n位数字

  

  例如:

  

var num=2011.145;
var res1=num.toFixed(2);    //保留2位小数,结果为2011.15
var res2=num.toFixed(3);    //保留3位小数,结果为2011.145
var res3=num.toFixed(6);    //保留6位小数,结果为2011.145000
var res4=num.toprecision(6);    //保留6位数字,结果为2011.15
var res5=num.toprecision(7);    //保留6位数字,结果为2011.145
var res6=num.toprecision(10);    //保留6位数字,结果为2011.145000
var res7=num.toprecision(2);    //保留6位数字,结果为2.0e+3

  toFixed函数中的参数是保留的小数点的位数,而toPrecision函数中的参数是保留除小数点以外所有数字数

原文地址:https://www.cnblogs.com/xiaotudou-datudou/p/4369048.html