js保留两位小数方法总结

JavaScript018

js保留两位小数方法总结,第1张

一、经典的“四舍五入”算法

第二种,当作字符串,使用正则匹配:

注意:如果是负数,请先转换为正数再计算,最后转回负数

再分享一个经典的解决四舍五入问题后js保留两位小数的方法:

二、Js取float型小数点后两位数的方法

小数点保留2位都可以用.toFixed(2)

改正后的zelc和Id函数如下(改动的地方见注释)

function zelc()

{

if((document.zobel.re.value <= 0 ) || (document.zobel.lces.value <= 0 ))

{

alert("请输入条件")

}

else

{

re = eval(document.zobel.re.value)

lces = eval(document.zobel.lces.value)

document.zobel.r1.value = eval(re*1.25).toFixed(2)//这里改一下

document.zobel.c1.value = eval((lces*1000000)/(re*re)).toFixed(2)//这里改一下

}

}

function ld()

{

if ((document.lp.impedance.value <=0) || (document.lp.attenuation.value <=0))

alert("请输入条件 !")

else

{

impedance = eval(document.lp.impedance.value)

attenuation = eval(document.lp.attenuation.value)

xval = eval(.05 * attenuation)

document.lp.r1.value = (impedance * (((Math.pow(10, xval)) - 1) / (Math.pow(10, xval)))).toFixed(2)//这里改一下

document.lp.r2.value = (impedance *( 1 / ((Math.pow(10, xval)) - 1))).toFixed(2)//这里改一下

}

}

需要准备的材料分别是:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html的<script>标签中,以圆桌率为例子,输入js代码:var a = 3.141592653var b = a.toFixed(2)document.body.innerText = b。

3、浏览器运行index.html页面,会打印出3.141592653格式化为小数点后2位的3.14。