Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - How to calculate percentage of width from value between min and max numbers?

I am struggling with simple problem. What is elegant way of achieving this.

I have 2 values minimum and maximum which can be positive or negative and a third value which is between them. Now I want to calculate position(percentage) of other given number, which in my case is the width of element.
For example here I want to find what is position in the range 0-200 that represents value -10 in range -500 to 600 ?

var min = -500;
var max = 600;
var value = -10;

var width = 200; 

var positionInWidth = ???;
question from:https://stackoverflow.com/questions/65924864/how-to-calculate-percentage-of-width-from-value-between-min-and-max-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can one-liner this but let's do this in a few steps to see how it works:

enter image description here

// first we get the total range
var length = max - min; // 1100
// then we offset the position by the start position
var positionInLength = value - min; // 490
// now we get the percent through the value is in the position
var valuePercent = positionInLength / length;
// or a one liner (value - min) / (max - min);
// Then finally, apply `width percentage`
const positionInWidth = width * valuePercent;

Or as a one liner:

const positionInWidth = width * ((value - min) / (max - min));


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...