|
| 1 | +--- |
| 2 | +Title: '.EPSILON' |
| 3 | +Description: 'Defines the smallest positive difference between 1 and the next representable floating-point number in JavaScript.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Web Development' |
| 7 | +Tags: |
| 8 | + - 'JavaScript' |
| 9 | + - 'Numbers' |
| 10 | + - 'Properties' |
| 11 | +CatalogContent: |
| 12 | + - 'introduction-to-javascript' |
| 13 | + - 'paths/front-end-engineer-career-path' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`.EPSILON`** property is a static member of the `Number` object in JavaScript. It represents the smallest difference between 1 and the next larger floating-point number, making it useful for handling floating-point precision and comparison in JavaScript. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +Number.EPSILON; |
| 22 | +``` |
| 23 | + |
| 24 | +**Parameters:** |
| 25 | + |
| 26 | +- `.EPSILON` is a static constant and does not take any arguments. |
| 27 | + |
| 28 | +**Return value:** |
| 29 | + |
| 30 | +Returns a constant value representing the smallest difference between 1 and the next greater representable floating-point number. The exact value is approximately `2.220446049250313e-16`. |
| 31 | + |
| 32 | +## Example |
| 33 | + |
| 34 | +In this example, `.EPSILON` is used to check if two floating-point numbers are nearly equal by comparing the difference to a very small threshold: |
| 35 | + |
| 36 | +```js |
| 37 | +function isEqual(a, b) { |
| 38 | + return Math.abs(a - b) < Number.EPSILON; |
| 39 | +} |
| 40 | + |
| 41 | +console.log(isEqual(0.1 + 0.2, 0.3)); |
| 42 | +``` |
| 43 | + |
| 44 | +The output for this code is: |
| 45 | + |
| 46 | +```shell |
| 47 | +true |
| 48 | +``` |
| 49 | + |
| 50 | +In this example, `.EPSILON` is used as a threshold to handle floating-point precision issues. The function compares the absolute difference between two numbers and returns `true` if that difference is smaller than `.EPSILON`, treating them as effectively equal. This helps avoid unexpected results when comparing decimal values like `0.1 + 0.2` and `0.3`. |
| 51 | + |
| 52 | +## Codebyte Example |
| 53 | + |
| 54 | +This codebyte example checks if the total cost of items matches the expected amount, accounting for floating-point precision: |
| 55 | + |
| 56 | +```codebyte/javascript |
| 57 | +function isEqual(a, b) { |
| 58 | + return Math.abs(a - b) < Number.EPSILON; |
| 59 | +} |
| 60 | +
|
| 61 | +const item1 = 0.1; |
| 62 | +const item2 = 0.2; |
| 63 | +const item3 = 0.3; |
| 64 | +
|
| 65 | +const total = item1 + item2 + item3; |
| 66 | +const expectedTotal = 0.6; |
| 67 | +
|
| 68 | +console.log("Is total correct?", isEqual(total, expectedTotal)); |
| 69 | +``` |
| 70 | + |
| 71 | +The `isEqual()` function checks if two numbers are nearly equal using `.EPSILON`. This handles minor floating-point differences in the calculated total. |
0 commit comments