假设我有一个值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?


当前回答

我使用(num-0.05). tofixed(1)来得到第二个小数。

其他回答

已经有一些合适的答案与正则表达式和算术计算,你也可以试试这个

function myFunction() {
    var str = 12.234556; 
    str = str.toString().split('.');
    var res = str[1].slice(0, 2);
    document.getElementById("demo").innerHTML = str[0]+'.'+res;
}

// output: 12.23
num = 19.66752
f = num.toFixed(3).slice(0,-1)
alert(f)

这将返回19.66

2021年6月更新

这将固定任何给定长度的数字而不舍入

let fixwithoutsurround = (v, l) => { const intPart = Math.trunc(v).toString() const fractionPart = v.toString().slice(v.toString(). indexof ('.') + 1) 如果(fractionPart。长度> l) { 返回(intPart.concat(数量”。’,fractionPart。片(0,l))) }其他{ const padding = intPart.concat('。’,fractionPart。padEnd (l ' 0 ')) 返回的 } } 12) console.log (FixWithoutRounding (123.123)

只需要截断数字:

function truncDigits(inputNumber, digits) {
  const fact = 10 ** digits;
  return Math.floor(inputNumber * fact) / fact;
}

一个简单的解决方案

const toFixedNoRounding = (value, digits) => {
  const factor = Math.pow(10, digits);

  return Math.trunc(value * factor) / factor;
};