Skip to content

Instantly share code, notes, and snippets.

@ahamed
Last active January 8, 2021 11:18
Show Gist options
  • Select an option

  • Save ahamed/8b1d8d67d42a1436feb55c422b6522f1 to your computer and use it in GitHub Desktop.

Select an option

Save ahamed/8b1d8d67d42a1436feb55c422b6522f1 to your computer and use it in GitHub Desktop.
Converting string to number using JavaScript.
/**
* Ways to convert a numeric string to a number.
*
* @author Sajeeb Ahamed
*/
const str = '343';
// Using parseInt method.
number = parseInt(str);
// Using 0 bit right shifting.
// Careful this only works with 32 bits numbers.
number = str >> 0;
// Using Number constructor
// Note: For real number string it returns original real number
number = Number(str);
// Using unary plus (+) operator
// Note: For real number string this also returns original real number
number = +str;
// Multiplying or dividing by 1
number = str * 1; // or
number = str / 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment