Truncate number to two decimal places without rounding

前端 未结 30 3122
再見小時候
再見小時候 2020-11-22 09:08

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+\"
30条回答
  •  春和景丽
    2020-11-22 09:46

    This worked well for me. I hope it will fix your issues too.

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



提交回复
热议问题