@jgCarroll/

equivalentNumbers

JavaScript

A common interview question.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
console.log(900.9 === 3 * 300.3) // false

console.log(900.9 == 3 * 300.3) // false

// JavaScript deals with decimals in a funky way, as below

console.log(300.3 * 3) // logs 900.9000000000001

// =============================================
// some fixes

console.log((300.3 * 3).toFixed(2)) // logs 900.90
console.log(Number((300.3 * 3).toFixed(2))) // logs 900.9
console.log((300.3 * 3).toFixed(1)) // logs 900.9

console.log(Number((300.3 * 3).toPrecision(12))) // logs 900.900000000

console.log((300.3 * 10) * 3 / 10) // logs 900.9

console.log(900.9 === (300.3 * 10) * 3 / 10) // evaluates to true
Native Browser JavaScript