javascript - 不同范围的百分比值
问题描述
我从昨天开始尝试在 JavaScript 中找到一个公式(也是数学公式),它返回来自 3 个不同案例的给定百分比的值。
Example:
range A = [0, 10 ] - percentage 25% => value will be 2.5
range B = [0, 100] - percentage 50% => value will be 50
but how do I treat this 2 cases?:
case 1 = range [-5, 5 ] - percentage for example 50% => value will be 0
case 2 = range [-10, 0 ] - percentage for example 25% => value will be -7.5
case 3 = range [-11, -1] - percentage for example 30% => value will be ?
解决方案
这是你的公式:试试这个。
const percentage = function(x, y, perc){
// x is start point
// y is end point
// so you need length of this range (between x and y) and we subtract x from y
// and dividing to 100 (because 100% is full range between x and y)
// when we divide it to 100, the result is 1% of the range
// then we multiply it to percentage we want for example 25%
// and adding x to result. Because we started from x;
return ((y-x)/100)*perc+x;
}
console.log(percentage(0,10,25));
console.log(percentage(0,100,50));
console.log(percentage(-5,5,50));
console.log(percentage(-10,0,25));
console.log(percentage(-11,-1,30));
推荐阅读
- javascript - 使用 PHP 和 Ajax 返回文件地址
- dataset - 每周收到的项目 KPI
- function - 如何将方法绑定到 Kotlin 中的名称?
- oracle - 在物化视图创建中考虑同一张表的子查询
- javascript - 仅使用 Babel/Webpack 进行转译/polyfilling
- amazon-web-services - AWS Cloudwatch 警报简化警报以配置到整个粘合作业集群
- sql - 如何在另一列之前找到最新日期的行?
- android-studio - 无法识别的 Android Studio 版本
- css - css动画向左移动,重新出现在右侧并继续向左
- amazon-ec2 - WSO2 API 管理器 - TypeError 无法在 API 中获取尝试