|
-
Impressive Click
[Problem] Rounding off to the nearest multiple of a variable
Okay, I wanted to know if anyone knows how to create a formula that rounds a number off to the nearest variable. Note, that I am not trying to round the number to the nearest integer but to the nearest mulitple of a variable here are some examples:
code:
var staticNum = 42;
var changingNum = 35;
now I want to round changingNum to the nearest multiple of staticNum.
In this case I want changingNum to equal 42. How do I do it? Then how would I do it this way:
code:
var changingNum = 86;
In this case, I want changingNum to equal 84, because 84 is the nearest multiple of 42. Please help. If you don't understand what I mean, ask questions because I will be happy to answer.
-
SaphuA
Here's a try, I'm asuing you're not alowing negative multples and allowing the use of multiples of 1.
//--Edit little bug found, will add new code in few min's 
Hope you can understand it, I tried to add comments but I suck at explaining stuff like this
Last edited by SaphuA; 01-20-2005 at 06:11 PM.
-
Impressive Click
thank you so much except there was a little problem with it. I had to change Math.floor to Math.round, because I wanted it to round to the nearest multiple. But thanks! Heres the new script, for anyone who wants it:
code:
var startN = 42;
var newN = 158;
if (newN<startN) {
newN = startN;
} else {
var multiples = Math.round(newN/startN);
newN = multiples*startN;
if (multiples>startN/2) {
newN += startN;
}
}
trace(newN);
-
SaphuA
Hey,
I see you've already seen my bugged version of the code I thought it was done, but I didn't test it too well. Here's a working version (atleast I think ), but I haven't tested it with negative values though. I suggest you use this code as it's easier to read and to adjust for use with negative values.
code:
var srtN = 23;
var oldN = 234;
var newN;
//--
if (oldN%srtN<srtN/2) {
newN = oldN-(oldN%srtN);
} else {
newN = oldN-(oldN%srtN)+srtN;
}
trace(newN);
SaphuA
Last edited by SaphuA; 01-20-2005 at 06:43 PM.
-
Impressive Click
well if you wanted to make it a negative value can't you just change everything to positvie and then use newN * -1 after its solved to make it a negative number?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|