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


当前回答

2016年11月5日更新

新的答案,总是准确的

function toFixed(num, fixed) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
    return num.toString().match(re)[0];
}

由于javascript中的浮点数学总是有边缘情况,所以之前的解决方案在大多数情况下都是准确的,这是不够的。 有一些解决方案,如num.toPrecision, BigDecimal.js和accounting.js。 然而,我相信仅仅解析字符串是最简单的,而且总是准确的。

基于@Gumbo接受的答案的良好编写的正则表达式的更新,这个新的toFixed函数将始终按预期工作。


老答案,并不总是准确的。

固定功能:

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

其他回答

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

功能召唤(形式) 原型。值,圆 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方法在某些情况下会失败,所以要非常小心。

这对我来说很有效。我希望它也能解决你的问题。

function toFixedNumber(number) {
    const spitedValues = String(number.toLocaleString()).split('.');
    let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';
    decimalValue = decimalValue.concat('00').substr(0,2);

    return '$'+spitedValues[0] + '.' + decimalValue;
}

// 5.56789      ---->  $5.56
// 0.342        ---->  $0.34
// -10.3484534  ---->  $-10.34 
// 600          ---->  $600.00

function convertNumber(){ var result = toFixedNumber(document.getElementById("valueText").value); document.getElementById("resultText").value = result; } function toFixedNumber(number) { const spitedValues = String(number.toLocaleString()).split('.'); let decimalValue = spitedValues.length > 1 ? spitedValues[1] : ''; decimalValue = decimalValue.concat('00').substr(0,2); return '$'+spitedValues[0] + '.' + decimalValue; } <div> <input type="text" id="valueText" placeholder="Input value here.."> <br> <button onclick="convertNumber()" >Convert</button> <br><hr> <input type="text" id="resultText" placeholder="result" readonly="true"> </div>

parseInt比Math.floor快

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

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

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

// 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));
}

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

希望能有所帮助!

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)