强制保留2位小数

强制保留2位小数,如:2,会在2后面补上00.即2.00

console.log(toDecimal2(6))
console.log(toDecimal2(61))
console.log(toDecimal2(61.1))
console.log(toDecimal2(61.888))
   //强制保留2位小数,如:2,会在2后面补上00.即2.00 
   function toDecimal2(x) { 
      var f = parseFloat(x); 
      if (isNaN(f)) { 
        return false; 
      } 
      var f = Math.round(x*100)/100; 
      var s = f.toString(); 
      var rs = s.indexOf('.'); 
      if (rs < 0) { 
        rs = s.length; 
        s += '.'; 
      } 
      while (s.length <= rs + 2) { 
        s += '0'; 
      } 
      return s; 
    } 

你可能感兴趣的:(js)