Calculating percentage

Whing Dela Cruz
Whing Dela Cruz used Ask the Experts™
on
Hi experts, what is the best solution to get percentage profit between the capital cost and selling price? My code below is not consistent where if the amount will have a comma or like 1,000.00 it will no longer work.  

function CalculateProfit()
{
	var sp = document.getElementById("A5").value;
	var uc = document.getElementById("A3").value;
	var prt = (sp /(.01 * uc) - 100);
	//var n = prt.toFixed(2);
	var n = prt.toFixed(0);
	document.getElementById("A4").value = n + "%"; 

}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Full Stack Developer
Commented:
To remove the comma from the entered amount, you can try the following regex:
sp =sp .replace(/\,/g,'');

Open in new window


So update your code as follows:

function CalculateProfit()
{
	var sp = document.getElementById("A5").value;
        sp=sp.replace(/\,/g,'');
	var uc = document.getElementById("A3").value;
        uc =uc.replace(/\,/g,'');
	var prt = (sp /(.01 * uc) - 100);
	//var n = prt.toFixed(2);
	var n = prt.toFixed(0);
	document.getElementById("A4").value = n + "%"; 

}

Open in new window

Author

Commented:
Thank you Banshi, Its working!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial