乘法后,我希望输出为 2 位小数?怎么做?

问题描述

我想从 gien 输入计算乘法。但是,我希望输出不超过 2 位小数。

例如12.24 和 13.17 的乘积是 161.2008。我希望输出截断为 2 位小数,即输出应为 161.20。

我不是专业人士,只是为了让这个项目成功而工作。所以如果你们能编辑我的代码并教我,那也将不胜感激。

在这里粘贴了我项目的部分代码

function dbkcalc()
        {
  
        var decde = (document.getElementById('DECDAPR').value * document.getElementById('DECDAPC').value);
        document.getElementById('DECDE').value= decde;
        }
<style>
    td
        {
        width: 50%;
        border: 1px solid ORANGE;
        }

      

</style>

<body>

<table align="center">


    <tr>
        <td>DECDAPR</td>
        <td><input id="DECDAPR"></td>
    </tr>

    <tr>
        <td>DECDAPC</td>
        <td><input id="DECDAPC"></td>
    </tr>

    <tr>
        <td colspan=2>
            <input id="CALDIF" type="button" class="button" value="CALculaTE" onClick="dbkcalc()">
        </td>
    </tr>

    <tr>
        
        <td><U>DECDE</U></td>
        <td class="declared"><U><output id="DECDE" type="number"></U></td>
    </tr>

</table>

</body>

解决方法

使用 Math.round() 方法: 对于四舍五入的 2 个十进制数字:

var a = 12.24;
var b = 13.17;
var c = a * b;
c = Math.round(c * 100) / 100;
console.log(c);

如果您想截断而不是四舍五入,请使用 toFixed() 方法:

var a = 12.24;
var b = 13.17;
var c = a * b;
c = c.toFixed(2);
console.log(c);

这将截断为两位数。

,

This has already been asked here. 你真的应该在发帖之前尝试谷歌这些简单的东西。但无论如何只需将 1 javascript 代码行更改为 document.getElementById('DECDE').value = decde.toFixed(2);