Skip to content

Instantly share code, notes, and snippets.

@vpodk
Last active April 20, 2020 21:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vpodk/c2ad215e1021a16fd3e1 to your computer and use it in GitHub Desktop.
Save vpodk/c2ad215e1021a16fd3e1 to your computer and use it in GitHub Desktop.
Manipulating numbers in JavaScript.
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);
@yairEO
Copy link

yairEO commented Apr 20, 2020

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

@vpodk
Copy link
Author

vpodk commented Apr 20, 2020

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