Darlington
Darlington

Reputation: 3

Profit Calculation in two decimal places Javascript

In my script, I run this function to calculate profit of entries on my products table from the MySQL db. The concerning fields are defined as decimal (10,2). It's a sales platform where I want the profit column to be able to calculate in two decimal places when adding new products into the system. Like selling price = 50.60, original price =40.20, so the profit column should be able to give me 10.40 as the answer. Thus 50.60-40-20.

This the function i used

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;

        }

These are the script I used to add new product where selling price represents txt1 in the function. Whiles ,original price and profit columns represent txt2 and txt3 respectively in the function.

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

My script is working correctly but thats not what I wish for. The profit column is not able to subtract decimals from another decimal value, hence, It only show results in Integer. I expect If selling price = 50.60, original price =40.20, the profit column should be able to give me 10.40 as the answer. Thus 50.60-40-20.

Upvotes: 0

Views: 140

Answers (1)

Nick
Nick

Reputation: 147166

Your problem is that you need to use parseFloat, not parseInt, to use your inputs as floating point numbers. Also you should use toFixed(2) on the output to ensure it is rounded to two decimal places.

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>

Upvotes: 1

Related Questions