functiontoDecimal2(strData){//检查非法字符串if(!strData){return""}if(!parseFloat(strData)){return""}letret=parseFloat(strData)ret=Math.round(ret*100)/100//四舍五入,保留2位小数,如果是1000,保留3位小数//如果传入的字符串是整数则处理if(ret.toString().indexOf(".")<0){ret=ret.toFixed(2)}returnret.toString()}console.log("2.561=",toDecimal2("2.561"))//2.561=2.56console.log("2.567=",toDecimal2("2.567"))//2.567=2.57console.log("2.0=",toDecimal2("2.0"))//2.0=2.00console.log("2.00=",toDecimal2("2.00"))//2.00=2.00console.log("2=",toDecimal2("2"))//2=2.00console.log("100=",toDecimal2("100"))//100=100.00console.log("=",toDecimal2(""))//=console.log("sdf=",toDecimal2("sdf"))//sdf=总结:这里主要要使用两个技术点,使用Math.round(ret*100)/100将满足小数条件的小数保留在一步中。使用float.toFixed(2)对不满足小数条件的使用float.toFixed(2),比如“2”,先parseFloat,把它转成float,但是显示的时候,小数点后面的0默认点,然后使用toFixed(2),很明显显示为2.00
