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');
}
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');
}
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) {
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');
}