How to generate random numbers in Javascript [duplicate] - javascript

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generating random numbers in Javascript
Hi..
I want to generate random numbers (integers) in javascript within a specified range. ie. 101-999. How can I do that. Does Math.random() function supports range parameters ?

Just scale the result:
function randomInRange(from, to) {
var r = Math.random();
return Math.floor(r * (to - from) + from);
}

The function below takes a min and max value (your range).
function randomXToY(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return Math.round(randVal);
}
Use:
var random = randomXToY(101, 999);
Hope this helps.

Math.floor(Math.random()*898)+101

Related

Why my function returns int without sum of 1, or it sums random number [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 3 months ago.
I'm trying to convert Steam ID 32bit to Steam ID 64bit.
My javascript function is not working right but same function in python works fine. Python function is copied from How can I get a steamid 64 from a steamID in python
function steamidTo64(steamid) {
let steam64id = 76561197960265728; // Valve's magic constant
let id_split = steamid.split(":");
steam64id += parseInt(id_split[2]) * 2;
if (id_split[1] == "1") {
steam64id += 1;
}
return steam64id;
}
Using input of STEAM_1:1:191000236 function should return 76561198342266201, but instead it returns 76561198342266200
Using input of STEAM_1:1:3645504 function should return 76561197967556737, but it returns 76561197967556740
Using input of STEAM_0:0:570629725 function should return 76561199101525178, but it returns 76561199101525180
You will need to use BigInt since 76561197960265728 is greater than 9007199254740992 (1 digit longer), and so arithmetic operations on this number are inaccurate and can lead to incorrect results.
function steamidTo64(steamid) {
let steam64id = 76561197960265728n;
const id_split = steamid.split(":");
steam64id += BigInt(id_split[2]) * 2n;
if (id_split[1] === "1") steam64id += 1n;
return steam64id;
}
// Result is BigInt
console.log(steamidTo64("STEAM_1:1:191000236").toString());

Javascript wrong math [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);

Format number using pure javascript [duplicate]

This question already has answers here:
Javascript Thousand Separator / string format [duplicate]
(15 answers)
How to format a number with commas as thousands separators?
(50 answers)
Closed 7 years ago.
I have written a code to calculate number of votes. I am getting the output as 138405, 150000 etc.
I want these figures to be formatted like this 138,405.
How do I achieve this using pure javascript?
Depending on your browser targets you could use Number.prototype.toLocaleString() which will format your numbers based on locale which you can specify. Examples are on the linked page below.
See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
For example:
var number = 123456.789;
console.log(number.toLocaleString('en-US'));
// → 123,456.789
If no locale is specified the users browser locale will be used.
You need to decide what the convention is first. Do you want your commas to separate two digits, or three?
Let's imagine that it's 3, as per the usual convention.
1000 should become 1, 000
10000 should become 10,000
100000 should become 100,000
1000000 should become 1,000,000
The code to make that happen can be as trivial as:
function formatWithComma(interval, num) {
const digits = String(num).split('').reverse();
const output = [];
digits.forEach(function (digit, index, digits) {
output.push(digit);
if ((index + 1) % interval === 0 && (index + 1) < digits.length) {
output.push(',');
}
});
return output.reverse().join('');
}
This function expects to be called with an interval at which commas will be inserted and a number, from which to build a formatted string.
formatWithComma(3, 12345) === "12,345"
formatWithComma(2, 12345) === "1,23,45"
You could take this one step further and use Javascript's partial application mechanism to create a format function with the first argument preloaded.
var format = formatWithComma.bind(this, 3);
After that, any calls to format will insert commas at every 3rd digit.
I came up with this function. It works fine for me.
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

Generate number but exclude one number in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need to generate one random number between a range but exclude one specific number.
I thought I can do this like that but it didn't work.
function randNum(num){
var randNumber=Math.floor(Math.random()*num)+1;
if(randNumber==2){
randNum(num);
}else{
alert(num);
}
}
randNum(4);
What is the problem?
Thanks.
Assuming you want to output the random number and not the num-parameter, you just have to change the alert to:
alert(randNumber)
Like in this fiddle http://jsfiddle.net/3urFC/
Are you trying to alert the randNum that you generated? Right now you will alert the function argument (in this case the number 4) everytime. I think you want to change it to alert(randNumber).
Math.random returns a number between 0 and 1. See the documentation on MDN.
Also, see this question about generating a random number in a specific range.
So, you have two problems: one, you're not generating a random number in the range you think you are, and two, you're not using the random number you generated.
I made this fiddle that does something similar to what you described.
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateRandomWithExclusion(exclude, min, max) {
var num = getRandomInt(min, max);
while (num === exclude) {
num = geRandomInt(min, max);
}
return num;
}
generateRandomWithExclusion(2, 0, 10) // returns an integer between 0 and 10 that is not 2
You pass the number you want to exclude and a range of min and max, and get a random integer in that range that isn't the number you want excluded.
function randNum(num) {
var randNumber;
do { randNumber = Math.floor(Math.random()*num)+1; } while(randNumber==2);
return randNumber;
}
randNum(4);
There is a typho as other has stated.
Also I would rearrange it this way:
function randNum(num){
var numberToExclude=2;
var randNumber=Math.floor(Math.random()*(num-1))+1;
if(randNumber>=numberToExclude) {
randNumber+=1;
}
alert(randNumber);
}
randNum(4);
Here is a JSFidle
http://jsfiddle.net/2F5Md/1/

Javascript sum of values in table [duplicate]

This question already has answers here:
How to format a float in javascript?
(14 answers)
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 9 years ago.
I've succesfully used this code to calculate sums in a table:
var $overall = 0;
$("tr.sum").each(function()
{
var $qnt = $(this).find("td").eq(0);
var $price = $(this).find("td").eq(1);
console.log($qnt+" | "+$price);
var sum = parseFloat($price.text()) * parseFloat($qnt.text());
$(this).find("td").eq(2).text(sum);
$overall+= sum;
});
$("#total").text($overall); });
I changed one line to avoid rounding errors:
var sum = parseFloat((parseFloat($price.text().replace(',', '.')) * parseFloat($qnt.text().replace(',', '.'))).toFixed(2));
It works fine. But I can't solve the problem to round the total sum to two decimal places.
$("#total").text($overall);
I tried toFixed(2). But this results in a string and not a number.
Any help would be appreciated!
Thanks, Mike
after doing all calculation make it like this
$overall.toFixed(2);

Categories

Resources