kirgy
kirgy

Reputation: 1607

Scaling a range of numbers in PHP?

I'm developing some PHP code which is communicating with a piece of hardware which is moving a physical hand on a clock. Basically, I've got a range of numbers (minutes) between 000 and 180 which correspond to servo positions 000 to 180.

The problem I am facing is I now have found that the servo can only move to values between 000 and 165.

Is there a way of scaling a given number in the range of 000 to 180 to a range of 000 to 165? I've been racking my brains on this one, any help would be greatly appreciated.

Example function:

function convertScale($handVal)
{
 //some code to convert scale from 000-180 to 000-165
 return $convertedPos;
}

Upvotes: 1

Views: 893

Answers (1)

wallyk
wallyk

Reputation: 57774

Can it take floating point?

function convertScale($handVal)
{
    return $handVal * 165.0 / 180.0;
}

If not, rounding to nearest integer is hopefully okay:

function convertScale($handVal)
{
    return round($handVal * 165.0 / 180.0);
}

---Edit---
As alluded to in comments, a 3-digit string is easily provided by:

function convertScale($handVal)
{
    return sprintf ("%03d", round($handVal * 165.0 / 180.0));
}

Upvotes: 5

Related Questions