Calculate the percentage of a number using Javascript
Contents
Percentage of a number
A percentage is a portion of a whole expressed as a number between 0 and 100 rather than as a fraction. For example, Students wants to calculate the percentage for marks. Similarly employee calculates percentage for the tax and salary hike. Lets see how to calculate the percentage of a number with example.
Percentage formula
P% * X
P – the percentage that we want to calculate. % – percent sign means divide by 100. X – a number
Example : 10 % of 350
Here we trying to calculate the 10 percentage of 350. First we need to multiply 10 with 350 and the result will be divided by 100. The output value is 35.
Another way to calculate percentage is (number 1/number2) * 100. Lets implement this calculation in the javascript
Calculate the percentage using javascript
1 2 3 4 5 6 7 8 |
<script type="text/javascript"> function percentage() { var a = Number(document.getElementById("t1").value); var b = Number(document.getElementById("t2").value) / 100; alert(a*b); } </script> |
We can design the percentage calculator using HTML and then we can execute this javascript to get the output value. We need to create text boxes to get the values and the calculate button is required to perform the percentage calculation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <style> .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; cursor: pointer; } </style> <title></title> <script type="text/javascript"> function percentage() { var a = Number(document.getElementById("t1").value); var b = Number(document.getElementById("t2").value) / 100; alert(a*b); } </script> </head> <body> <strong>What is <input name="" id="t1"> % of <input name="" id="t2"> ? </strong><br><br> <button class = "button" onclick="percentage()">Calculate Percentage</button> </body> </html> |
Percentage calculator in HTML and Javascript
Recommended Articles