根据您的编辑以及有关您想要的更多详细信息,以下是一些实现该公式的 JavaScript:
function percent_difference(target, actual) {
if (target === 0 || actual === 0) {
if (actual > target) {
return 100;
} else if (actual < target) {
return -100;
} else {
return 0;
}
}
var relative_to = Math.min(Math.abs(actual), Math.abs(target));
var distance_from_target_to_actual = actual - target;
var fraction_difference = distance_from_target_to_actual / relative_to;
return 100 * fraction_difference;
}
我试图避免不必要if
的语句以保持代码简单。
该函数通过了这些测试:
function test_percent_difference() {
console.log("percent_difference(-10, -20)", percent_difference(-10, -20), "should be", -100);
console.log("percent_difference(-5, 50)", percent_difference(-5, 50), "should be", 1100);
console.log("percent_difference(30, -10)", percent_difference(30, -10), "should be", -400);
console.log("percent_difference(15, 0)", percent_difference(15, 0), "should be", 100);
console.log("percent_difference(0, 0)", percent_difference(0, 0), "should be", 0);
}
您可以在这个 jsFiddle的浏览器中自己运行它。