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:
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
CodePudding user response:
I don't know why your min and max are reversed, but here you go:
const result1 = someMagick(0.5, [-26, -5]);
const result2 = someMagick(1, [-26, -5]);
console.log(result1, result2)
function someMagick(percent, [max, min]) {
return (max - min) * percent min
}
CodePudding user response:
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.
CodePudding user response:
Based on your explanation, it looks like result2 is incorrect. It should be -5 because 100% is the second value.
The function assumes that x < y in the array [x, y]
function someMagick(percent, [min, max]) {
// Range between min and max
let range = max - min;
percent /= 100;
// Finding value between min and max using the percent
let result = min (range * percent);
//Round to hundredths
return parseFloat(result.toFixed(2));
}
const result1 = someMagick(50, [-26, -5]);
const result2 = someMagick(100, [-26, -5]);
console.log(result1, result2)
// -15.5, -5