Math.random() applied as a percentage? - javascript

so I have this code that is giving me a random number for both top and left attribute of some images.
var random1 = Math.ceil(Math.random() * 500);
var random2 = Math.ceil(Math.random() * 500);
$(document).ready(function () {
$('#randomp').css('top', random1);
$('#randomp').css('left', random2);
});
The problem is that I would be prefer to randomize a number between 1 and 100%. Is that possible?

Math.floor(Math.random() * 100) + 1 + '%'

Since Math.random returns number that is random, not less than 0 and less than 1, you have just to multiply result by 99 instead of 500 to get a number beetween 1 and 100%.
Finally, the code should be as follows:
var random1 = Math.round(Math.random() * 99) + 1;
var random2 = Math.round(Math.random() * 99) + 1;

This gives you a number between 0 and 100 (both included):
Math.floor(Math.random() * 101);
Math random will give you a number between 0 (included) and 1 (excluded)
If you multiply that number with 101, it will give you a number between 0 (included) and 101 (excluded)
Math.floor will return the the largest integer less than or equal to the above number.

Not sure if you want it rounded or not, so here's both:
console.log( rando(1, 100) + "%" );
console.log( rando(1, 100, "float") + "%" );
<script src="https://randojs.com/1.0.0.js"></script>
This uses randojs.com to make the randomness simple and readable. If you need to know more, check out the website.

Related

Calculate percentage increase using math formula

I have a function that calculates percentage increase of 2 numbers:
const 1st_num = 50
const 2nd_num = 100
percentage = ((1st_num - 2nd_num) / 1st_num) * 100 // -100
It seems correct but what if the 1st number is 1?
((1 - 50) / 1) * 100 // -4900
I don't see it making sense anymore. What am I missing?
If you are computing a delta variation in percentage between 2 numbers, it should be the other way around:
variation = ((num2 - num1) / num1) * 100
Last but not least, your delta can be over 100%
For example, imagine at
t1=10 and t2=11 -> your delta will be computed like this : (11 - 10)/10, so you have an increase of 10%
but if you have t1=10 and t2=100 -> your delta will become (100 - 10)/10, so you have an increase of 900%
First up all your question is more suitable to somewhere in math forums:
Your formula is right just change it as follows to get increase change in positive numbers:
percentage = ((2nd_num - 1st_num) / 1st_num) * 100 // 100%
However your treatment with 1 is exactly right.
4900 % In other words 49 times increase in value.
You can't use variable name starts with numbers
const fst_num = 50
const snd_num = 100
percentage = ((snd_num -fst_num) / fst_num) * 100
const fst_num = 70192.32
const snd_num = 17548.08
const percentage = ( 100 - ( ( fst_num - snd_num ) / fst_num ) * 100 );

What's the easiest way to convert a number to a percentage in JavaScript?

I'm calculating the difference in size of images after they've been resized by the user. I take the images new width and divide it by the natural width. This is the code:
Math.round( (img.width / naturalWidth) * 100) / 100
The numbers I get as a result can look like the following (and the numbers commented out are what I'd like to convert them to).
0 // 0%
1 // 100%
1.2 // 120%
1.39402 // 139%
1.39502 // 140%
21.56 // 216%
0.4 // 40%
0.44 // 44%
0.1 // 10%
0.01 // 1%
0.005 // 1%
0.0049 // 0%
Never negative numbers. I need to round these numbers and then convert them into strings represented as percentages. Is there an easy and straightforward way to accomplish this?
You can use Math.round like this:
Math.round((img.width/ naturalWidth) * 100));
A simple example:
var a = 1.2;
var b = 1;
alert(Math.round((a / b) * 100) + '%'); // 120%
This should do the trick:
const formatAsPercentage = x => `${Math.round(x * 100)}%`
You can use it as:
formatAsPercentage(.05) // => "5%"
First multiply the number by 100 then use Math.round() to round the result. Finally, add the percent sign:
Math.round(img.width / naturalWidth * 100) + "%";
I've used in own project
function calculatePercent(config){
var currentProgressPercent;
var totalRecords = Number.parseFloat(config.totalRecords);
var current = Number.parseFloat(config.current);
currentProgressPercent = 0;
if (!(isNaN(totalRecords) || isNaN(current))) {
currentProgressPercent = (totalRecords === 0 ? 100 : Math.round((current / totalRecords) * 100));
}
currentProgressPercent += '%';
return currentProgressPercent;
}
var input = [0, 1, 1.2, 2.156, 0.4, 0.44, 0.1, 0.01, 0.005, 0.0049];
input.forEach(function(value){
alert(calculatePercent({current:value, totalRecords: 1}));
});
You might do some refactoring for your needs in variable names.

How to generate random integers which are multiples of 30 in JavaScript

I'm trying to generate random integers that are are multiples of 30 in JavaScript.
That is:
0 60 0 180 120 ...... and so on
in range between 0 to 360 for example
So I am looking for a function something like this:
function (_range,_multi)
{
Math.round(...);
return rndNum;
}
Generate a random number between 0 and 12 (range) and multiply by 30 (multi):
Math.floor(Math.random() * 12) * 30
This gives you [0, 360) (so you never get 360)
Here's a live demo that shows a full working function - the general idea is that you multiply by (max/multiple), floor the value, then multiply it by the multiple:
function generate(min, max, multiple) {
var res = Math.floor(Math.random() * ((max - min) / multiple)) * multiple + min;
return res;
}
alert(generate(0, 360, 30));
Seems like that should work.
function randomMultiple(max, mult) {
return Math.floor(Math.random() * (max / mult)) * mult;
}
Thus a call of randomMultiple(360, 30) would produce an element of G with
G = { y = 30 * x | 0 < x < 12 }

JavaScript - random multiple of 20 between 0 - 580

In Javascript, how do I create a random even number multiplied by 20 between 0 - 580?
E.g.: 220, 360, 180, 0 (min), 400, 200, 580 (max)
You want increments of 20, so what you really need is an integer in the range 0 to 29, and then multiply with 20. Example:
var max = (580/20) + 1;
var result = 20 * (Math.floor(Math.random())*max)
We are adding one to max, because Math.random() is a uniformly distributed number between (inclusive 0) and (exclusive 1), so since we use Math.floor, the maximum must be 1 larger.
This way creates a random number, then rounds it down to the nearest multiple:
When you need 0 <= randomMultiple <= max
var random = Math.random() * (580 + 20);
randomMultiple = random - (random % 20);
When you need 0 <= randomMultiple < max
var random = Math.random() * 580;
randomMultiple = random - (random % 20);
Use a principle like this: Generate random number between two numbers in JavaScript
Keeping in mind that if you want your max result to be 580, then the maximum integer you want to multiply by 20 would be 29 (or 580/20). Then just add some logic to make sure the integer is even.
Ta da!
Try use this:
var result = parseInt(Math.random()*30)*20;
29*20 = 580
Math.random() return [0..1)
result between 0..580, step by 20
Here is a generic javascript one-liner that can be used for any range, and any multiple.
Essentially, what we are trying to do here is figure out a range, 0 to N, which when multiplied by our given multiple stays within the range [0,max-min].
In this case N, is simply, (max - min)/multiple, or range/multiple.
Once we have N, we can use Math.random() to get a random number between 0-N, and multiply it with multiple. Next, we just add min.
We assume that min and max are already multiples of multiple.
Note the additional +1 to the input of Math.random() is because Math.random() returns a number between 0 (inclusive) and 1 (exclusive). So, Math.random() can never return 1. If we didn't account for that we would never be able to include the max number in our results.
/*
* Returns a random number within range [min,max]
*
* min and max must be multiples of multiple
* (note that 0 is a multiple of all integers)
*/
function randomMultiple (min, max, multiple) {
return Math.floor(Math.random() * (((max - min)/multiple)+1)) * multiple + min;
}
console.log(randomMultiple(0, 580, 20));

round up nearest 0.10

I need to round up to the nearest 0.10 with a minimum of 2.80
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = (dist/1609.344).toFixed(2) + " miles = £" + (((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(2);
}
any help would be appreciated
var number = 123.123;
Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);
If you need to round up, use Math.ceil:
Math.max( Math.ceil(number2 * 10) / 10, 2.8 )
Multiply by 10, then do your rounding, then divide by 10 again
(Math.round(12.362 * 10) / 10).toFixed(2)
Another option is:
Number(12.362.toFixed(1)).toFixed(2)
In your code:
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = Number((dist/1609.344).toFixed(1)).toFixed(2)
+ " miles = £"
+ Number((((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(1)).toFixed(2);
}
To declare a minimum, use the Math.max function:
var a = 10.1, b = 2.2, c = 3.5;
alert(Math.max(a, 2.8)); // alerts 10.1 (a);
alert(Math.max(b, 2.8)); // alerts 2.8 because it is larger than b (2.2);
alert(Math.max(c, 2.8)); // alerts 3.5 (c);
This is a top hit on google for rounding in js. This answer pertains more to that general question, than this specific one. As a generalized rounding function you can inline:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
Test it out below:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
const test = (num, grain) => {
console.log(`Rounding to the nearest ${grain} for ${num} -> ${round(num, grain)}`);
}
test(1.5, 1);
test(1.5, 0.1);
test(1.5, 0.5);
test(1.7, 0.5);
test(1.9, 0.5);
test(-1.9, 0.5);
test(-1.2345, 0.214);
var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;
to round to nearest 0.10 you can multiply by 10, then round (using Math.round), then divide by 10
Round to the nearest tenth:
Math.max(x, 2.8).toFixed(1) + '0'
Round up:
Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)

Categories