假设我有一个值15.7784514,我想把它显示为15.77,没有舍入。

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

结果:

15.8
15.78
15.778
15.7784514000 

如何显示15.77?


当前回答

谢谢,Martin Varmus

function floorFigure(figure, decimals){
     if (!decimals) decimals = 2;
     var d = Math.pow(10,decimals);
     return ((figure*d)/d).toFixed(decimals);
};

floorFigure(123.5999)    =>   "123.59"
floorFigure(123.5999, 3) =>   "123.599"

我做了一个简单的更新,我得到了适当的舍入。更新如下

return ((figure*d)/d).toFixed(decimals);

删除parseInt()函数

其他回答

这里的答案对我没有帮助,它总是四舍五入,或者给我错误的小数。

我的解决方案将您的小数转换为字符串,提取字符,然后将整个东西作为数字返回。

function Dec2(num) {
  num = String(num);
  if(num.indexOf('.') !== -1) {
    var numarr = num.split(".");
    if (numarr.length == 1) {
      return Number(num);
    }
    else {
      return Number(numarr[0]+"."+numarr[1].charAt(0)+numarr[1].charAt(1));
    }
  }
  else {
    return Number(num);
  }  
}

Dec2(99); // 99
Dec2(99.9999999); // 99.99
Dec2(99.35154); // 99.35
Dec2(99.8); // 99.8
Dec2(10265.985475); // 10265.98
num = 19.66752
f = num.toFixed(3).slice(0,-1)
alert(f)

这将返回19.66

这些解决方案确实有效,但对我来说似乎没有必要这么复杂。我个人喜欢用模运算符来得到除法运算的余数,然后去掉余数。假设num = 15.7784514:

num-=num%.01;

这相当于说num = num - (num % .01)。

将数字转换为字符串,匹配到小数点后第二位:

功能召唤(形式) 原型。值,圆 var with2Decimals toString () = num。竞赛(- ^ \ d + (? d: \。{0.2的)? /)[0 - 9] rounded。价值2决定 的 <形式onsubmit=“报复性calc(this)”> 原始号码:<输入方式/> <br /> ' Rounded number: < name name=" Rounded" type="文本" placeholder="readonly" readonly> < / form >

与toString不同,toFixed方法在某些情况下会失败,所以要非常小心。

给你。另一种解决问题的方法:

// For the sake of simplicity, here is a complete function:
function truncate(numToBeTruncated, numOfDecimals) {
    var theNumber = numToBeTruncated.toString();
    var pointIndex = theNumber.indexOf('.');
    return +(theNumber.slice(0, pointIndex > -1 ? ++numOfDecimals + pointIndex : undefined));
}

注意在最后一个表达式之前使用了+。这就是将截断的、切片的字符串转换回数字类型。

希望能有所帮助!