JS 四舍五入

/****************************************************************************
* Round off a primitive numeric to the given decimal places
*
* num - 传入的数字.
* decPlaces - 小数的位数.
*
* 返回一个四舍五入的字符串; 如果不是一个有效数字,返回 "NaN"
****************************************************************************/
function round(num, decPlaces)
{
  var decSep = ".";  // Decimal separator
  var buff;          // Buffer used to determine rounded number
  var i;             // Location of the decimal place
 
  var descrep;
  var segments;
  var leftSide;
  var rightSide;
 
  num = Number(num);

  if(isNaN(num))
    return("NaN");

  buffer = "" + Math.round(num * Math.pow(10, decPlaces)) / Math.pow(10,
                                                                   decPlaces);
 
  // 注意!! Math.round does not work correctly; so, we must double check
  // the formatting...
  i = buffer.indexOf(decSep);
  segments = buffer.split(".");

  if(i == 0)
    buffer = "0" + buffer;
 
  if(segments.length == 2) 
    descrep = decPlaces - segments[1].length;
  else
  {
    descrep = decPlaces;
   
    if(descrep > 0)
      buffer += decSep;
  }
 
  for(var j=0; j<descrep; j++)
    buffer += "0";
     
  return(buffer);
}// END round

你可能感兴趣的:(J#)