您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

javascript 数字保留数字后面小数点

作者:佚名    责任编辑:admin    更新时间:2022-06-22

   看到很多人有这保留数字后面小数点的需求,但是大多数是自己写一个函数来截取,还要考虑四舍五入啥的,写起来还挺复杂的。

  其实javascript的Number对象是有一个保留小数点后面的小数的方法的:toFixed,它是四舍五入后的数。

  我一度担心IE6不支持这个方法,看到MDN里面说这个方法是javascript1.5才出来。专门在IE6下试了下,是完全支持

  toExponential([fractionDigits]) :将数字按科学计数法格式返回,其中的fractionDigits值小数点后保留的位数。

  toFixed([fractionDigits]) :将数字按指定的小数点位数返回,其中的fractionDigits值小数点后保留的位数。

  toPrecision([precision]) :将数字按指定的精度返回(这个精度不是指小数点后几位),其中precision是指定的精度值。

  例子如下:

  代码如下

  var n = 12345.6789;

  n.toFixed(); // Returns 12346

  n.toFixed(1); // Returns 12345.7

  n.toFixed(6); // Returns 12345.678900

  (1.23e+20).toFixed(2); // Returns 123000000000000000000.00

  (1.23e-10).toFixed(2); // Returns 0.00

  2.34.toFixed(1); // Returns 2.3

  -2.34.toFixed(1); // Returns -2.3

  (-2.24).toFixed(1); // Returns -2.2

  转换函数,这段代码来源于国外一个论坛。

  代码如下

  function roundNumber(number,decimals) {

  var newString;// The new rounded number

  decimals = Number(decimals);

  if (decimals < 1) {

  newString = (Math.round(number)).toString();

  } else {

  var numString = number.toString();

  if (numString.lastIndexOf(".") == -1) {// If there is no decimal point

  numString += ".";// give it one at the end

  }

  var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number

  var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with

  var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want

  if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated

  if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point

  while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {

  if (d1 != ".") {

  cutoff -= 1;

  d1 = Number(numString.substring(cutoff,cutoff+1));

  } else {

  cutoff -= 1;

  }

  }

  }

  d1 += 1;

  }

  if (d1 == 10) {

  numString = numString.substring(0, numString.lastIndexOf("."));

  var roundedNum = Number(numString) + 1;

  newString = roundedNum.toString() + '.';

  } else {

  newString = numString.substring(0,cutoff) + d1.toString();

  }

  }

  if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string

  newString += ".";

  }

  var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;

  for(var i=0;i

  //var newNumber = Number(newString);// make it a number if you like

  document.roundform.roundedfield.value = newString; // Output the result to the form field (change for your purposes)

  }