小数点后两位的利润计算Javascript

时间:2019-08-28 22:37:52

标签: javascript

在我的脚本中,我运行此函数来计算来自MySQL数据库的产品表上条目的利润。有关领域 被定义为十进制(10,2)。这是一个销售平台,在向系统中添加新产品时,我希望利润列能够在两位小数位计算。就像销售价格= 50.60,原始价格= 40.20,因此“利润”列应该能够给我10.40作为答案。因此50.60-40-20。

这是我使用的功能

function sum() {

        var txtFirstNumberValue = document.getElementById('txt1').value;
        var txtSecondNumberValue = document.getElementById('txt2').value;
        var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
        if (!isNaN(result)) {
            document.getElementById('txt3').value = result;

        }

这些是我用来添加新产品的脚本,其中销售价格代表函数中的txt1。而函数价格中的原始价格和利润列分别代表txt2和txt3。

<span>Selling Price : </span>
<input type="text" id="txt1" style="width:265px; height:30px;" name="price" onkeyup="sum();" Required><br> 
<span>Original Price : </span>
<input type="text" id="txt2" style="width:265px; height:30px;" name="o_price" onkeyup="sum();" Required><br>
 <span>Profit : </span>
<input type="text" id="txt3" style="width:265px; height:30px;" name="profit" readonly><

我的脚本运行正常,但是那不是我想要的。利润列不能从另一个十进制值中减去十进制,因此,它仅以整数显示结果。 我希望如果销售价格= 50.60,原始价格= 40.20,则利润栏应该可以给我10.40作为答案。因此是50.60-40-20。

1 个答案:

答案 0 :(得分:1)

您的问题是您需要使用parseFloat而不是parseInt来将输入用作浮点数。另外,您应该在输出上使用toFixed(2),以确保将其舍入到小数点后两位。

function sum() {

        var txtFirstNumberValue = document.getElementById('txt1').value;
        var txtSecondNumberValue = document.getElementById('txt2').value;
        var result = parseFloat(txtFirstNumberValue) - parseFloat(txtSecondNumberValue);
        if (!isNaN(result)) {
            document.getElementById('txt3').value = result.toFixed(2);

        }
        }
<span>Selling Price : </span>
<input type="text" id="txt1" style="width:265px; height:30px;" name="price" onkeyup="sum();" Required><br> 
<span>Original Price : </span>
<input type="text" id="txt2" style="width:265px; height:30px;" name="o_price" onkeyup="sum();" Required><br>
<span>Profit : </span>
<input type="text" id="txt3" style="width:265px; height:30px;" name="profit" readonly><br>