Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create value between two numbers by percentage

I have 2 arrays: [-26, -5] [-5.3, 2.3], and a percentage value from 0 to 100 that changes on scroll.

I need a function that generates a number by percentage between two numbers, where percentage 0 is the first value from the array, and where 100 percent is the second value. 50% is exactly in the middle of the two numbers. After receiving a number, reduce it to hundredths.

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result1 = someMagick(50%, [-26, -5]);
const result2 = someMagick(100%, [-26, -5]);

console.log(result1, result2)
// -16, -26

I don’t have any thoughts how to do it, please help

>Solution :

function someMagick(percentage, numbers) {
  // Convert percentage value to decimal
  const decimalPercentage = percentage / 100;

  // Calculate range between numbers
  const range = numbers[1] - numbers[0];

  // Calculate result by adding first number in array to the product of the percentage value and the range
  const result = numbers[0] + (decimalPercentage * range);

  // Return result rounded to the nearest hundredth
  return Math.round(result * 100) / 100;
}

// Example usage
const result1 = someMagick(50, [-26, -5]);
const result2 = someMagick(100, [-26, -5]);

console.log(result1, result2);
// -16, -26

You can then use this function to generate a number by percentage between two numbers in your code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading