kgpmurray
kgpmurray

Reputation: 202

How to calculate value percentage value between two points

This is probably a really dumb question but..

I have 3 values for example lets call them minX, currentX and maxX. im looking for a way to calculate the percentage of maxX that currentX represents. e.g if maxX is 50 and minX is 40 and currentX is 45 then i want to get 50% this is all pretty basic but the problem im having is when one or more of my variables is a negative number.

Any help would be appreciated, also let me know if i didn't explain myself well enough

Upvotes: 5

Views: 14943

Answers (3)

Tim
Tim

Reputation: 15237

(currentX - minX) / (maxX - minX)

Will give you the percentage, even if you're using negative numbers (as long as maxX > currentX > minX). Also make sure you're dealing with doubles/floats, not ints. otherwise you'll need to cast.

Upvotes: 21

user652038
user652038

Reputation:

Unity already made the function for you. Multiply by 100.

http://docs.unity3d.com/Documentation/ScriptReference/Mathf.InverseLerp.html

Upvotes: 0

BradW
BradW

Reputation: 79

You'll need to have some error check in place to ensure it's a positive number.

if (X >= 0)

..do you something

else

Value inputted was less then 0

Upvotes: 0

Related Questions