Introduction
In this lab, we will explore the concept of reversing a number in JavaScript. We will learn how to use built-in methods such as split(), reverse(), and join() to achieve this task. By the end of this lab, you will have a deeper understanding of how to manipulate numbers in JavaScript.
Reversing a Number
To reverse a number using JavaScript, you can use the reverseNumber() function with the following steps:
- Convert the number
nto a string usingObject.prototype.toString(). - Use
String.prototype.split(),Array.prototype.reverse()andArray.prototype.join()to get the reversed value ofnas a string. - Convert the string back to a number using
parseFloat(). - Preserve the sign of the number using
Math.sign().
Here's the code for the reverseNumber() function:
const reverseNumber = (n) =>
parseFloat(`${n}`.split("").reverse().join("")) * Math.sign(n);
You can test the function with these examples:
reverseNumber(981); // 189
reverseNumber(-500); // -5
reverseNumber(73.6); // 6.37
reverseNumber(-5.23); // -32.5
Summary
Congratulations! You have completed the Reverse Number lab. You can practice more labs in LabEx to improve your skills.