How to calculate the percentage between 3 numbers in javascript?
valueStart: 120 valueEnd: 970
valueCenter:360 | need to redeem this value where it remains within the standard of 0 to 100%
The value of 120 equals 0%. The value of 970 equals 100¨%.
CodePudding user response:
Question: How to calculate the percentage between 3 numbers in javascript?
Like this
function calculatePercentageOf3 (firstVal, midVal, lastVal)
{
return (midVal - firstVal) / (lastVal - firstVal) * 100;
}
Demo
const valueStart = 120;
const valueEnd = 970;
const valueCenter = 360;
function calculatePercentageOf3 (firstVal, midVal, lastVal)
{
return (midVal - firstVal) / (lastVal - firstVal) * 100;
}
const percentage = calculatePercentageOf3 (valueStart,valueCenter, valueEnd)
document.querySelector (".output").innerText = `Result: ${percentage}`;
console.log(percentage); // Outputs: 28.235294117647058
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div >output</div>
</body>
</html>
CodePudding user response:
You can do it like this:
const start_value = 120;
const end_value = 970;
const calculate_percentage = (input_number) => {
if(input_number < start_value) return 0;
if(input_number > end_value) return 100;
return (input_number-start_value)/(end_value-start_value)*100;
}
console.log(calculate_percentage(120))
console.log(calculate_percentage(500))
console.log(calculate_percentage(970))
CodePudding user response:
Somebody good at math would be able to turn three numbers into three percentages out of 100. var xwidth = ( x/( x y)*100); var ywidth = ( 100-xwidth); //var zwidth = ( 100-ywidth); javascript