Format number to always show 2 decimal places

前端 未结 30 2844
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 08:17

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1            


        
30条回答
  •  甜味超标
    2020-11-21 08:35

    var num1 = "0.1";
    document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
    
    var num2 = "1.341";
    document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
    
    var num3 = "1.345";
    document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
    span {
        border: 1px solid #000;
        margin: 5px;
        padding: 5px;
    }
    
    
    

提交回复
热议问题