保留小数位数的函数--js

 控制保留几位有效小数的js函数

//Code CreateBy abandonship 2007.03.12
function FormatAfterDotNumber( ValueString, nAfterDotNum )
{
        var ValueString,nAfterDotNum ;
  var resultStr,nTen;
  ValueString = ""+ValueString+"";
  strLen = ValueString.length;
  dotPos = ValueString.indexOf(".",0);
  if (dotPos == -1)
        {
    resultStr = ValueString+".";
    for (i=0;i                {
      resultStr = resultStr+"0";
          }
    return resultStr;
  }
  else
        {
    if ((strLen - dotPos - 1) >= nAfterDotNum ){
      nAfter = dotPos + nAfterDotNum  + 1;
      nTen =1;
      for(j=0;j        nTen = nTen*10;
      }
      resultStr = Math.round(parseFloat(ValueString)*nTen)/nTen;
      return resultStr;
    }
    else{
      resultStr = ValueString;
      for (i=0;i<(nAfterDotNum  - strLen + dotPos + 1);i++){
        resultStr = resultStr+"0";
      }
      return resultStr;
    }
  }
}

应用时只需要FormatAfterDotNumber( '数字字符串', 保留小数位数 );
for example:









你可能感兴趣的:(JavaScript)