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
How to convert array of decimal strings to array of integer strings without decimal in JavaScript
We are required to write a JavaScript function that takes in an array of decimal strings. The function should return an array of strings of integers obtained by flooring the original corresponding decimal values of the array.
For example, If the input array is ?
const input = ["1.00","-2.5","5.33333","8.984563"];
Then the output should be ?
const output = ["1","-2","5","8"];
Method 1: Using parseInt()
The parseInt() function parses a string and returns an integer. It automatically truncates decimal parts.
const input = ["1.00","-2.5","5.33333","8.984563"];
const roundIntegers = arr => {
const res = [];
arr.forEach((el, ind) => {
res[ind] = String(parseInt(el));
});
return res;
};
console.log(roundIntegers(input));
[ '1', '-2', '5', '8' ]
Method 2: Using Math.floor() with map()
A more concise approach using map() and Math.floor() for proper flooring behavior:
const input = ["1.00","-2.5","5.33333","8.984563"];
const floorIntegers = arr => {
return arr.map(str => String(Math.floor(parseFloat(str))));
};
console.log(floorIntegers(input));
[ '1', '-3', '5', '8' ]
Method 3: Using Number() Constructor
Converting to number first, then truncating and converting back to string:
const input = ["1.00","-2.5","5.33333","8.984563"];
const truncateIntegers = arr => {
return arr.map(str => String(Math.trunc(Number(str))));
};
console.log(truncateIntegers(input));
[ '1', '-2', '5', '8' ]
Comparison
| Method | Behavior | Negative Numbers | Performance |
|---|---|---|---|
parseInt() |
Truncates towards zero | -2.5 ? -2 | Fast |
Math.floor() |
Floors down | -2.5 ? -3 | Medium |
Math.trunc() |
Truncates towards zero | -2.5 ? -2 | Fast |
Key Points
-
parseInt()andMath.trunc()truncate towards zero -
Math.floor()always rounds down (different behavior for negatives) - Remember to convert back to strings if string output is required
- Use
map()for cleaner, functional programming approach
Conclusion
Use parseInt() for simple truncation or Math.trunc() for explicit truncation behavior. Choose Math.floor() only when you need true floor operation for negative numbers.
