0

I am very new to JavaScript trying to understand some math logic in JavaScript,Any idea why my code inside if condition is not executing?

index.js

var a = 0.1,
    b = 0.2,
    c = Math.random(a + b);

if(c === 0.3) {
    console.log('fun');
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
hussain
  • 6,587
  • 18
  • 79
  • 152

2 Answers2

2

Math.random() gives a random number between zero and one.

Use Math.round() to round the floating number and thus remove floating point difference.

var a = 0.1,
    b = 0.2,
    c = Math.round((a + b) * 100) / 100; // Round numbers to single decimal point

if (c === 0.3) {
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

Math.random() Returns a random number between 0 (inclusive) and 1 (exclusive) and does NOT take any arguments.

Therefor, Math.random() by itself can generate 0.3 without any tweaking.

try this:

var c =  Math.round(Math.random()* 10 ) / 10;

if (c === 0.3)
   console.log('fun');
}
Rana
  • 1,675
  • 3
  • 25
  • 51