How to subtract a percentage from a number in Javascript? -
here code subtracts 2 var.
function calculate() { var mybox1 = document.getelementbyid('ax').value; var mybox2 = document.getelementbyid('by').value; var myresult = mybox1 * mybox2; var mybox3= document.getelementbyid('mybox3'); mybox.value = myresult ; }
this take out percentage.
function calculate() { var mybox1 = document.getelementbyid('ax').value; var mybox2 = document.getelementbyid('by').value; var myresult = mybox1 * mybox2; var mybox3= document.getelementbyid('mybox3'); var percentage = myresult/mybox3 -2%; mybox3.value = myresult ; }
you have several problems in code, apart mixin between subtract , multiplication:
- in first function using
mybox
undefined
should usemybox3
instead. - and in second function, dividing number input type should replace
myresult/mybox3-2
myresult/(mybox3.value-2)
, append%
sign need use+"%"
. - in end of second function
mybox3
value should takepercentage
, notresult
variable. - don't use same name
calculate
2 functions.
this updated code:
function calculate1() { var mybox1 = document.getelementbyid('ax').value; var mybox2 = document.getelementbyid('by').value; var myresult = mybox1 * mybox2; var mybox3 = document.getelementbyid('mybox3'); mybox3.value = myresult; } function calculate2() { var mybox1 = document.getelementbyid('ax').value; var mybox2 = document.getelementbyid('by').value; var myresult = mybox1 * mybox2; var mybox3 = document.getelementbyid('mybox3'); var percentage = myresult / (mybox3.value - 2) +" %"; mybox3.value = percentage; }
edit:
if want subtract 2%
multiplication result
should calculate value of 2%
first, subtract result
:
function calculate() { var mybox1 = document.getelementbyid('mybox1').value; var mybox2 = document.getelementbyid('mybox2').value; var myresult = mybox1 * mybox2; //2% of myresult ===> myresult × 2 ÷ 100 var substpercentage = myresult*2/100; console.log(substpercentage); var mybox3 = document.getelementbyid('mybox3'); var percentage = myresult - substpercentage; mybox3.value = percentage; }
this the updated fiddle.
Comments
Post a Comment