I have the following values
x = 7.81;
y = 178.32;
z = (x/y)*100;
The percentage must be 4%
for the above result. How can I calculate the percentage using JavaScript?
You pretty much have valid Javascript there, with the exception of the mixed case X (Javascript is case sensitive)
var x, y, z;
x=7.81;
y=178.32;
z=(x/y)*100;
console.log( z );
To get the result to two decimal places (2DP) you can use .toFixed()
:
console.log( z.toFixed(2) );
var x = 7.81;
var y = 178.32;
var z = (x/y)*100;
z stores your percentage then.
Perhaps you're struggling with rounding:
var x = 7.81;
var y = 178.32;
alert( Math.round(x / y * 100) + '%' ); // 4%
Try this:
var a = 7.81;
var b = 178.32;
var c = a/b;
var result = c*100;
alert(result);
var x,y,z;
x = 7.81;
y = 178.32;
z = (Number(x)/Number(y)) * 100;
console.log(z);
(or)
alert(z);
You can create a function that you can use in different ways like below
function percentage(x, y)
{
return (x / y) * 100;
}
console.log(percentage(7.81, 178.32) + '%');
console.log(percentage(7.81, 178.32).toFixed(2) + '%'); // rounded to 2 decimal places
console.log(percentage(7.81, 178.32).toFixed(0) + '%'); // rounded to integer
See fiddle for demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.