user2330002
user2330002

Reputation:

Why doesn't this code generate the number 0?

Was wondering why my code doesn't generate the number zero, every number is randomly generated from 1-9.

What will I need to change to include 0-9 range.

function GenerateCaptcha() {
var chr1=Math.ceil(Math.random() * 9)+ '';

Many Thanks

Upvotes: 1

Views: 255

Answers (5)

PEPEGA
PEPEGA

Reputation: 2283

You can use the super short version ~~(Math.random() * 10) to generate a number between 0-9 Math.random() * 10) will return a number with a bunch of decimals ex:4.324843245 So what we can do is to convert it to a int, the easiest way to do this in javascript is with ~~ it's exactly the same as parseInt

console.log(~~(Math.random() * 10))
console.log(parseInt(Math.random() * 10))
console.log(Math.random() * 10)

Upvotes: 3

iCPSoni
iCPSoni

Reputation: 136

To generate 0 you need to use Math.floor() in place of Math.ceil.

For Example

function GenerateCaptcha() {
var chr1=Math.floor(Math.random() * 9)+ '';

Math.ceil gives 1 if it's below 1 i.e. 0.xxx

Math.floor gives 0 when number is. greater than 0 and less than 1. i.e. from 0.0 to 0.99

Upvotes: 0

Sarvesh Mahajan
Sarvesh Mahajan

Reputation: 924

Replace Math.ceil(Math.random() * 9)+ ''; with Math.floor(Math.random() * 9)+ '';

Upvotes: 1

kooskoos
kooskoos

Reputation: 4879

Use Math.floor() for generating 0 as one of the random numbers.

Upvotes: 1

Nicolas
Nicolas

Reputation: 8670

From the MDN doc

The Math.ceil() function always rounds a number up to the next largest whole number or integer.

This means, if you get a number between 0 and 1, it will be rounded to 1.

You could leave it as is, or use Math.floor instead.

Or even better, Math.round, as Levi Johansen suggested. This will round to the closest integer.

Upvotes: 4

Related Questions