Last active
April 20, 2020 21:20
-
-
Save vpodk/c2ad215e1021a16fd3e1 to your computer and use it in GitHub Desktop.
Manipulating numbers in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var n = 1; | |
console.log(n.toFixed(2)); | |
// To change the number directly: | |
// 1. Use parentheses: | |
console.log((1).toFixed(2)); | |
// 2. Use two dots: | |
console.log(1..toFixed(2)); | |
// Number binary representation: | |
console.log(20..toString(2)); | |
console.log('10100' == 20..toString(2)); | |
// Decimal number to hex: | |
console.log(255..toString(16)); | |
console.log('ff' == 255..toString(16)); | |
// hex to decimal number: | |
console.log(parseInt('ff', 16)); | |
console.log(255 == parseInt('ff', 16)); | |
// Math.floor shorthand: | |
var n = 123.45; | |
console.log(n | 0); | |
console.log(Math.floor(n)); | |
console.log(Math.floor(n) == n | 0); | |
// Convert to unsigned int32: | |
console.log(n >>> 0); | |
// Convert to signed int32: | |
console.log(n | 0); | |
console.log(n >> 0); | |
// parseInt(n, 10) shorthand: | |
var s = '123.45'; | |
console.log(~~s); | |
console.log(parseInt(s, 10)); | |
console.log(parseInt(s, 10) == ~~s); | |
// Math.round shorthand: | |
var n = 123.45; | |
console.log(~~(0.5 + n)); | |
console.log(Math.round(n)); | |
console.log(Math.round(n) == ~~(0.5 + n)); | |
// Math.floor shorthand: | |
var n = 123.45; | |
console.log(0 | n); | |
console.log(Math.floor(n)); | |
console.log(Math.floor(n) == 0 | n); | |
// Math.ceil shorthand: | |
// Update: Does not work correctly with integers. | |
var n = 123.45; | |
console.log(~~n + 1); | |
console.log((0 | n) + 1); | |
console.log(Math.ceil(n)); | |
console.log(Math.ceil(n) == ~~n + 1); | |
console.log(Math.ceil(n) == (0 | n) + 1); | |
// Cast to Number shorthand: | |
var s = '123.45'; | |
console.log(+s); | |
console.log(Number(s)); | |
console.log(Number(s) == +s); | |
// isNaN shorthand: | |
var s = 'abc'; | |
console.log(!+s); | |
console.log(isNaN(s)); | |
console.log(isNaN(s) == !+s); |
Wrong logic in
Math.ceil
- Will not act like is should for integer values:console.log(Math.ceil(1) == ~~1 + 1) // 1 == 2
All examples have the same basic flaw
@yairEO, Great catch, thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrong logic in
Math.ceil
- Will not act like is should for integer values:All examples have the same basic flaw