Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Numbers and operands to words in JavaScript
We are required to write a JavaScript function that takes in a string of some mathematical operation and return its literal wording.
Problem
Converting mathematical expressions like "5 - 8" into readable words like "Five Minus Eight" requires mapping numbers and operators to their text equivalents.
Approach
We'll create two lookup objects: one for operators and another for numbers. Then parse the input string and convert each part using these mappings.
Example
Following is the code ?
const str = '5 - 8';
const convertToWords = (str = '') => {
const operators = {
"+" : "Plus",
"-" : "Minus",
"*" : "Times",
"/" : "Divided By",
"**" : "To The Power Of",
"=" : "Equals",
"!=" : "Does Not Equal",
}
const numbers = {
1 : "One",
2 : "Two",
3 : "Three",
4 : "Four",
5 : "Five",
6 : "Six",
7 : "Seven",
8 : "Eight",
9 : "Nine",
10 : "Ten",
}
let parts = str.split(' ');
let result = '';
let operatorFound = false;
// Check if operator exists
for (const [key, value] of Object.entries(operators)) {
if(key === parts[1]) {
operatorFound = true;
break;
}
}
if(!operatorFound) return "That's not an operator!";
// Convert first number
for (const [key, value] of Object.entries(numbers)) {
if(key === parts[0]) {
result += `${value} `;
}
}
// Convert operator
for (const [key, value] of Object.entries(operators)) {
if(key === parts[1]) {
result += `${value}`;
}
}
// Convert second number
for (const [key, value] of Object.entries(numbers)) {
if(key === parts[2]) {
result += ` ${value}`;
}
}
return result;
}
console.log(convertToWords(str));
Output
Five Minus Eight
Testing Different Operations
console.log(convertToWords('3 + 7'));
console.log(convertToWords('9 * 2'));
console.log(convertToWords('10 / 5'));
console.log(convertToWords('4 ** 3'));
Three Plus Seven Nine Times Two Ten Divided By Five Four To The Power Of Three
How It Works
The function splits the input string by spaces to get three parts: first number, operator, and second number. It uses lookup objects to find the text equivalents and concatenates them into a readable sentence.
Conclusion
This approach effectively converts mathematical expressions to words using object mappings. The function handles various operators and provides clear error messages for invalid inputs.
