如何将结果修改为2位小数?

时间:2016-03-10 01:23:42

标签: javascript

我试图这样做,所以我的面积和周长计算器结果固定为2位小数。怎么做?

<script>

var $ = function(id) {
        return document.getElementById(id);
    }

    //calculate

    function calculator() {
        var recLength = $("recLength").value ;
        var recWidth =  $("recWidth").value ;
        $("recArea").value = recLength * recWidth ;
        $("recPerim").value = 2 * recWidth + 2 * recLength ; 



    }

    window.onload = function() 
    {
        $("calculate").onclick = calculator;
    }   

</script>

</head>
<body>
    <main>
    <h1>Rectangle Area and Perimeter Calculator</h1>
        <div id="data">
            <label>Enter Length:</label>
            <input type="text" id="recLength"><br>

            <label>Enter Width:</label>
            <input type="text" id="recWidth"><br><br><br>

            <label>Rectangle Area:</label>
            <input type="text" id="recArea"><br>

            <label>Rectangle Perimeter:</label>
            <input type="text" id="recPerim"><br>
        </div>

1 个答案:

答案 0 :(得分:0)

欢迎使用SO,请使用toFixed()

$("recArea").value = (recLength * recWidth).toFixed(2)