Words To Numbers
Convert words to numbers. Optionally fuzzy match the words to numbers.
npm install words-to-numbers
If the whole string passed is a number then it will return a Number
type otherwise it will return the original string with all instances of numbers replaced.
TODO: Add functionality for parsing mixed numbers and words. PRs welcome.
Basic Examples
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('one hundred'); //100 wordsToNumbers('one hundred and five'); //105 wordsToNumbers('one hundred and twenty five'); //125 wordsToNumbers('four thousand and thirty'); //4030 wordsToNumbers('six million five thousand and two'); //6005002 wordsToNumbers('a thousand one hundred and eleven'); //1111 wordsToNumbers('twenty thousand five hundred and sixty nine'); //20569 wordsToNumbers('five quintillion'); //5000000000000000000 wordsToNumbers('one-hundred'); //100 wordsToNumbers('one-hundred and five'); //105 wordsToNumbers('one-hundred and twenty-five'); //125 wordsToNumbers('four-thousand and thirty'); //4030 wordsToNumbers('six-million five-thousand and two'); //6005002 wordsToNumbers('a thousand, one-hundred and eleven'); //1111 wordsToNumbers('twenty-thousand, five-hundred and sixty-nine'); //20569
Multiple numbers in a string
Returns a string with all instances replaced.
wordsToNumbers('there were twenty-thousand, five-hundred and sixty-nine X in the five quintillion Y')) // 'there were 20569 X in the 5000000000000000000 Y'
With Fuzzy Matching
Uses Jaro distance to find the best match for the number words. Don’t rely on this being completely accurate…
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('won huntred', {fuzzy: true}); //100 wordsToNumbers('too thousant and fiev', {fuzzy: true}); //2005 wordsToNumbers('tree millyon sefen hunderd and twinty sex', {fuzzy: true}); //3000726
Decimal Points
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('ten point five'); //10.5 wordsToNumbers('three point one four one five nine two six'); //3.1415926
Ordinal Numbers
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('first'); //1 wordsToNumbers('second'); //2 wordsToNumbers('third'); //3 wordsToNumbers('fourteenth'); //14 wordsToNumbers('twenty fifth'); //25 wordsToNumbers('thirty fourth'); //34 wordsToNumbers('forty seventh'); //47 wordsToNumbers('fifty third'); //53 wordsToNumbers('sixtieth'); //60 wordsToNumbers('seventy second'); //72 wordsToNumbers('eighty ninth'); //89 wordsToNumbers('ninety sixth'); //96 wordsToNumbers('one hundred and eighth'); //108 wordsToNumbers('one hundred and tenth'); //110 wordsToNumbers('one hundred and ninety ninth'); //199
Commonjs
const { wordsToNumbers } = require('words-to-numbers'); wordsToNumbers('one hundred'); //100;
Implied Hundreds
wordsToNumbers('nineteen eighty four', { impliedHundreds: true }); //1984 wordsToNumbers('one thirty', { impliedHundreds: true }); //130 wordsToNumbers('six sixty two', { impliedHundreds: true }); //662 wordsToNumbers('ten twelve', { impliedHundreds: true }); //1012 wordsToNumbers('nineteen ten', { impliedHundreds: true }); //1910 wordsToNumbers('twenty ten', { impliedHundreds: true }); //2010 wordsToNumbers('twenty seventeen', { impliedHundreds: true }); //2017 wordsToNumbers('twenty twenty', { impliedHundreds: true }); //2020 wordsToNumbers('twenty twenty one', { impliedHundreds: true }); //2021 wordsToNumbers('fifty sixty three', { impliedHundreds: true }); //5063 wordsToNumbers('fifty sixty', { impliedHundreds: true }); //5060 wordsToNumbers('fifty sixty three thousand', { impliedHundreds: true }); //5063000 wordsToNumbers('one hundred thousand', { impliedHundreds: true }); //100000
Here’s my JavaScript replacement of @Greg Hewgill’s Python module, minus the testing from the bottom of the code:
var Small = {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90
};
var Magnitude = {
'thousand': 1000,
'million': 1000000,
'billion': 1000000000,
'trillion': 1000000000000,
'quadrillion': 1000000000000000,
'quintillion': 1000000000000000000,
'sextillion': 1000000000000000000000,
'septillion': 1000000000000000000000000,
'octillion': 1000000000000000000000000000,
'nonillion': 1000000000000000000000000000000,
'decillion': 1000000000000000000000000000000000,
};
var a, n, g;
function text2num(s) {
a = s.toString().split(/[s-]+/);
n = 0;
g = 0;
a.forEach(feach);
return n + g;
}
function feach(w) {
var x = Small[w];
if (x != null) {
g = g + x;
}
else if (w == "hundred") {
g = g * 100;
}
else {
x = Magnitude[w];
if (x != null) {
n = n + g * x
g = 0;
}
else {
alert("Unknown number: "+w);
}
}
}
I got hung up a bit on the RegEx-ing and the for-each bug in IE, but here it is. A fairly decent conversion from Python to JavaScript, if I can say so myself, which I can’t. It needs some work — «One hundred and twenty» won’t work — but it’s good enough for now. Of course, thanks to @Greg Hewgill for the original, written in Python.
There are many ways to convert a string into a number using JavaScript. But what does that look like in code?
In this article, I will show you 11 ways to convert a string into a number.
Here’s an Interactive Scrim of How to Convert a String to a Number in JavaScript:
One way to convert a string into a number would be to use the Number()
function.
In this example, we have a string called quantity
with the value of "12"
.
const quantity = "12";
If we used the typeof
operator on quantity
, then it will return the type of string.
console.log(typeof quantity);
We can convert quantity
into a number using the Number
function like this:
Number(quantity)
We can check that it is now a number by using the typeof
operator again.
console.log(typeof Number(quantity));
If you tried to pass in a value that cannot be converted into a number, then the return value would be NaN
(Not a Number).
console.log(Number("awesome"));
How to convert a string to a number in JavaScript using the parseInt()
function
Another way to convert a string into a number is to use the parseInt()
function. This function takes in a string and an optional radix.
A radix is a number between 2 and 36 which represents the base in a numeral system. For example, a radix of 2 would represent the binary system, while a radix of 10 represents the decimal system.
We can use the quantity
variable from earlier to convert that string into a number.
const quantity = "12";
console.log(parseInt(quantity, 10));
What happens if I try to change the quantity
variable to "12.99"
? Will the result using parseInt()
be the number 12.99?
const quantity = "12.99";
console.log(parseInt(quantity, 10));
As you can see, the result is a rounded integer. If you wanted to return a floating point number, then you would need to use parseFloat()
.
How to convert a string to a number in JavaScript using the parseFloat()
function
The parseFloat()
function will take in a value and return a floating point number. Examples of floating point numbers would be 12.99 or 3.14.
If we modify our example from earlier to use parseFloat()
, then the result would be the floating point number of 12.99.
const quantity = "12.99";
console.log(parseFloat(quantity));
If you have leading or trailing whitespace in your string, then parseFloat()
will still convert that string into a floating point number.
const quantity = " 12.99 ";
console.log(parseFloat(quantity));
If the first character in your string cannot be converted into number, then parseFloat()
will return NaN
.
const quantity = "F12.99";
console.log(parseFloat(quantity));
How to convert a string to a number in JavaScript using the unary plus operator (+
)
The unary plus operator (+
) will convert a string into a number. The operator will go before the operand.
const quantity = "12";
console.log(+quantity);
We can also use the unary plus operator (+
) to convert a string into a floating point number.
const quantity = "12.99";
console.log(+quantity);
If the string value cannot be converted into a number then the result will be NaN
.
const quantity = "awesome";
console.log(+quantity);
How to convert a string to a number in JavaScript by multiplying the string by the number 1
Another way to convert a string into a number is to use a basic math operation. You can multiply the string value by 1 and it will return a number.
const quantity = "12";
console.log(quantity * 1);
As you can see, when we multiply the quantity
value by 1, then it returns the number 12. But how does this work?
In this example, JavaScript is converting our string value to a number and then performing that mathematical operation. If the string cannot be converted to a number, then the mathematical operation will not work and it will return NaN
.
const quantity = "awesome";
console.log(quantity * 1);
This method will also work for floating point numbers.
const quantity = "10.5";
console.log(quantity * 1);
How to convert a string to a number in JavaScript by dividing the string by the number 1
Instead of multiplying by 1, you can also divide the string by 1. JavaScript is converting our string value to a number and then performing that mathematical operation.
const quantity = "10.5";
console.log(quantity / 1);
How to convert a string to a number in JavaScript by subtracting the number 0 from the string
Another method would be to subtract 0 from the string. Like before, JavaScript is converting our string value to a number and then performing that mathematical operation.
const quantity = "19";
console.log(quantity - 0);
How to convert a string to a number in JavaScript using the bitwise NOT operator (~
)
The bitwise NOT operator (~
) will invert the bits of an operand and convert that value to a 32-bit signed integer. A 32-bit signed integer is a value that represents an integer in 32 bits (or 4 bytes).
If we use one bitwise NOT operator (~
) on a number, then it will perform this operation: -(x + 1)
console.log(~19);
But if we use two bitwise NOT operators (~
), then it will convert our string to a number.
const quantity = "19";
console.log(~~quantity);
This method will not work for floating point numbers because the result would be an integer.
const quantity = "19.99";
console.log(~~quantity);
If you tried to use this method on non-numeric characters, then the result would be zero.
const quantity = "awesome";
console.log(~~quantity);
This method does have its limitations because it will start to break for values that are considered too large. It is important to make sure that your number is between the values of a signed 32 bit integer.
const quantity = "2700000000";
console.log(~~quantity);
To learn more about the bitwise NOT operator (~
) , please read up in the documentation.
How to convert a string to a number in JavaScript using the Math.floor()
function
Another way to convert a string to a number is to use the Math.floor()
function. This function will round the number down to the nearest integer.
const quantity = "13.4";
console.log(Math.floor(quantity));
Just like in earlier examples, if we tried to use non-numeric characters, then the result would be NaN
.
const quantity = "awesome";
console.log(Math.floor(quantity));
How to convert a string to a number in JavaScript using the Math.ceil()
function
The Math.ceil()
function will round a number up to the nearest integer.
const quantity = "7.18";
console.log(Math.ceil(quantity));
How to convert a string to a number in JavaScript using the Math.round()
function
The Math.round()
function will round the number to the nearest integer.
If I have the value of 6.3, then Math.round()
will return 6.
const quantity = "6.3";
console.log(Math.round(quantity));
But if I changed that value to 6.5, then Math.round()
will return 7.
const quantity = "6.5";
console.log(Math.round(quantity));
Conclusion
In this article, I showed you 11 ways to convert a string to a number using JavaScript.
Here are the 11 different methods discussed in the article.
- using the
Number()
function - using the
parseInt()
function - using the
parseFloat()
function - using the unary plus operator (
+
) - multiplying the string by the number 1
- dividing the string by the number 1
- subtracting the number 0 from the string
- using the bitwise NOT operator (
~
) - using the
Math.floor()
function - using the
Math.ceil()
function - using the
Math.round()
function
I hope you enjoyed this article and best of luck on your JavaScript journey.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Sanchithasr
Posted on Dec 16, 2020
• Updated on Aug 19, 2021
1. Using parseInt()
parseInt()
parses a string and returns a whole number. Spaces are allowed. Only the first number is returned.
This method has a limitation though. If you parse the decimal number, it will be rounded off to the nearest integer value and that value is converted to string. One might need to use parseFloat()
method for literal conversion.
myString = '129'
console.log(parseInt(myString)) // expected result: 129
a = 12.22
console.log(parseInt(a)) // expected result: 12
Enter fullscreen mode
Exit fullscreen mode
2. Using Number()
Number()
can be used to convert JavaScript variables to numbers. We can use it to convert the string too number.
If the value cannot be converted to a number, NaN
is returned.
Number("10"); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Enter fullscreen mode
Exit fullscreen mode
3. Using Unary Operator (+)
The unary plus operator (+
) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn’t already.
const x = 25;
const y = -25;
console.log(+x); // expected output: 25
console.log(+y); // expected output: -25
console.log(+''); // expected output: 0
Enter fullscreen mode
Exit fullscreen mode
4. Using parseFloat()
parseFloat()
parses a string and returns a number. Spaces are allowed. Only the first number is returned.
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Enter fullscreen mode
Exit fullscreen mode
5. Using Math.floor()
The Math.floor()
function returns the largest integer less than or equal to a given number. This can be little tricky with decimal numbers since it will return the value of the nearest integer as Number.
str = '1222'
console.log(Math.floor(str)) // returns 1222
a = 12.22
Math.floor(a) // expected result: 12
Enter fullscreen mode
Exit fullscreen mode
6. Multiply with number
Multiplying the string value with the 1
which won’t change the value and also it will be converted to number by default.
str = '2344'
console.log(str * 1) // expected result: 2344
Enter fullscreen mode
Exit fullscreen mode
7. Double tilde (~~) Operator
We can use the double tilde operator to convert the string to number.
str = '1234'
console.log(~~str) // expected result: 1234
negStr = '-234'
console.log(~~negStr) // expected result: -234
Enter fullscreen mode
Exit fullscreen mode
Here is the comparison of the ways mentioned performance wise. Comment below if you know more methods.
Thank You
In JavaScript, you can represent a number is an actual number (ex. 42
), or as a string (ex. '42'
).
If you were to use a strict comparison to compare the two, it would fail because they’re two different types of objects.
var num1 = 42;
var num2 = '42';
if (num1 === num2) {
console.log(true);
} else {
console.log(false);
}
// Will log `false`
Today, let’s look at three different ways to convert a string into a number.
parseInt()
The parseInt()
method converts a string into an integer (a whole number).
It accepts two arguments. The first argument is the string to convert. The second argument is called the radix
. This is the base number used in mathematical systems. For our use, it should always be 10
.
var text = '42px';
var integer = parseInt(text, 10);
// returns 42
parseFloat()
The parseFloat()
method converts a string into a point number (a number with decimal points). You can even pass in strings with random text in them.
var text = '3.14someRandomStuff';
var pointNum = parseFloat(text);
// returns 3.14
Number()
The Number()
method converts a string to a number.
Sometimes it’s an integer. Other times it’s a point number. And if you pass in a string with random text in it, you’ll get NaN
, an acronym for “Not a Number.”
As a result of this inconsistency, it’s a less safe choice than parseInt()
and parseFloat()
. If you know the format of the number you’d like, use those instead. If you want the string to fail with NaN
if it has other characters in it, Number()
may actually be a better choice.
// Convert strings
Number('123'); // returns 123
Number('12.3'); // returns 12.3
Number('3.14someRandomStuff'); // returns NaN
Number('42px'); // returns NaN
Browser Compatibility
All three methods work in all modern browsers, and IE6 and up.
If you found this post useful, you might also like my Strings, Arrays, & Objects pocket guide, which features a ton of useful methods like these.