I'm looking for a way to round up a number to the next closest multiple of 250. So for example if I had the following JS:
var containerHeight = $("#container").height();
...And we imagine the value of "containerHeight" was 680px, I would want a way to round up to 750px (if the value was 1007, it should round up to 1250). I suspect this requires a solution that is more complex than I anticipate. Or perhaps jQuery has a built in function that will make this feasible?
I suppose this is more of a math question than it is a jQuery question (but my jQuery syntax knowledge is also a bit limited :)
Any ideas / bits of help are greatly appreciated,
Thanks!
containerHeight = Math.ceil(containerHeight / 250.0) * 250;
function NearestMultiple(i, j) {
alert(Math.ceil(i/ j) * j);
}
NearestMultiple(1007, 250); //returns 1250
See example at http://jsfiddle.net/SUya9/1/
Or what James said too!
EDIT: I see you wanted to round up all the time...Updated fiddle, but James got her in 1.
simple
var rounded = Math.ceil(value / round) * round;
For those that are working with integers, and want a solution that avoids intermediate floating point, use this:
int roundedUp = alignment * ((value + alignment - 1) / alignment);
or without the division:
int mod = value % alignment;
if (mod > 0)
value += (alignment - mod);
Related
I need a random number for many projects. For example, consider a video game in which the character finds a bag of gold that is partially empty. To set the percentage of gold in the bag, I would often use Math.floor(Math.random() * 100 + 0.5). Upon reading about geometric distribution, I sought to make a geometric distribution random percentage generator. After reading dozens of articles, I cobbled together this function:
function geoDistPercent() {
var rand = Math.random();
var prob = ???;
var rate = -Math.log(1 - prob);
var expr = -Math.log(rand)/rate;
return Math.floor(min + expr);
}
I have tried various numbers for prob = ???, but I am unable to find a way to add a maximum limit. I have tried many attempts at finding equations, to no avail. Pleas help!
UPDATE: I have just learned that geometric distribution has no maximum. I need a way to add one, so that results like "112%" are not generated. This could be done by adding a while loop and some control flow. It is the prob = ??? issue that I need help with.
Okay, after reviewing lots of articles and some other posts on SE, I cobbled together this solution:
function geoDist(min, max, prob) {
var q = 0;
var p = Math.pow(prob, 1 / (max - min));
while (true) {
q = Math.ceil(Math.log(1-Math.random()) / Math.log(p)) + (min - 1);
if (q <= max) {
return q;
}
}
}
It takes three parameters: min and max, as well as prob: the probability of getting max in one try. For generating percentages, geoDist(0,100,0.002) works exceptionally well. Thanks #NathanMerrill and #Bergi for providing helpful information
I am trying to Math.floor a scientific notation, but at one point the number gets too big and my current method doesn't work anymore. This is what I am using atm
var nr = (number+"").length - 4;
if( nr > 1 ) {
nr = Math.pow( 10, nr );
number= Math.floor(number/nr)*nr;
number= number.toExponential(3);
}
When it becomes a scientific notation by default, I think that's e20+, than my .length method doesn't work anymore since the length it returns isn't accurate. I can think of a work around, and that's to find out the number after e, and update my nr to Math.floor it properly, but it seems like so much work to do something so simple. Here's an example number 8.420960987929105e+79 I want to turn this into 8.420e+79, is there a way I can Math.floor the third decimal point always, no matter what the number is? As it stands when I use toExponential(3) it always rounds the number. My numbers can get as high as e+200 easily, so I need an easier way of doing what I'm currently doing.
Edit: managed to find a work around that works besides Connor Peet's answer for anyone who wants extra options
var nr = 8.420960987929105e+79+"";
var nr1 = nr.substr(0,4);
var nr2 = nr.substr(4, nr.length);
var finalNr = Number(nr1 + 0 + nr2).toExponential(3);
This way is more of a hack, it adds a 0 after the 4th number so when toExponential rounds it up, it gets 'floored' pretty much.
I wrote a little snippet to round a number to a certain number of significant figures some time ago. You might find it useful
function sigFigs(num, figures) {
var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);
return Math.round(num / delta) * delta;
}
sigFigs(number, 3); // => 8.420e+79
Can someone please help me with the simplest question ever.
var rate = (month * "0.004545");
I simply need to get rate to be the above value + 1.
I just need (X * Y) + 1
All values are numbers.
Would truly appreciate this, I have already spent 1 hour.
Just add (+) and remove the "s:
var rate = (month * 0.004545) + 1;
See Arithmetic operators on MDN.
Also ensure that month is defined without "s.
EDIT: As it appears that you aren't being able to get this to work, here's a JSFiddle that demonstrates the code working for me.
var prerate = parseFloat(month) * 0.004545;
var rate = ++prerate;
I got this answer earlier today for how to distort a random number seed toward one bound of the range:
var random = Math.pow(Math.random(), 2);
But that obviously distorts it along an exponential curve.. How can I make it linear?
Also, kind of relevant: I just created this simple script to visualize different types of distributions. It may be helpful for this question: http://jsfiddle.net/RTbrL/
It sounds like you are describing a one-sided triangular distribution.
If so, try
var random = 1.0 - Math.sqrt(Math.random());
or
var random = Math.abs(Math.random() - Math.random());
Like so?
var rand = Math.ceil( Math.random() * 5 ) % 5;
rand goes from 0 to 4.
% in Javascript is Modulus
How can I round the number using jQuery?
If the number is 3168 I want to print it as 32.
Or if the number is 5233 the result should be 52.
How can I do that?
Should I use the Math.round function?
Yes, you should use Math.round (after dividing by 100).
jQuery is a library for DOM traversal, event handling and animation built on top of JavaScript. It doesn't replace JavaScript and doesn't reimplement all its basic functions.
var num = 3168;
$('#myElement').text(Math.round(num/100));
I assume you mean divide by 100, then round? Or did you mean to have decimal places? (In which case, remove the /100 portion)
Also, this is just basic JavaScript. As another user mentioned, jQuery is to work with the document itself, not to perform math operations.
And here is a snippet from the jQuery math library1:
(function($){
$.round = Math.round;
})(jQuery);
$.round(3168 / 100) // 32
$.round(5233 / 100) // 52
1 Meant for humor only--this kind of functionality is provided out-of-the-box by JavaScript itself.
<script type='text/javascript'>
function jqROund(a) {
return Math.round(a/100);
}
</script>
<input type='text' id='numba' value='3168'>
<input type='button' onclick="alert( jqRound($('#numba').val() ) );">
The Math.round method does exactly you want and does not only ceil, or floor. It will round it to the nearest Integer.
If you're using the javascript Number object you can use the toFixed() method. I'm assuming those numbers are missing the decimal point. If not, divide by 100 and as above.
You can use this one :) roundMe(1.2345, 4)
function roundMe(n, sig) {
if (n === 0) return 0;
var mult = Math.pow(10, sig - Math.floor(Math.log(n < 0 ? -n: n) / Math.LN10) - 1);
return Math.round(n * mult) / mult;
}