How to reverse a number in JavaScript:
This post will show you how to reverse a number in JavaScript. For example, if the number is 123, it will change it to 321.
Number reverse programs in different programming languages uses similar algorithms. We will discuss different ways to reverse a number in this post. You will learn how to use a while loop, how to use the modulo operation, and how to find the floor value of a number in JavaScript with these examples.
We will also write it with HTML/CSS to calculate the reverse of a number by getting the number as input from the user.
Method 1: Algorithm to reverse a number with a loop:
To reverse a number, we need to keep picking the last digit of a number, and that number can be appended to the rightmost digit of the reversed number. On each step, we will pick the last digit and remove it from the original number.
For example, if the number is 123, we will first get the last digit i.e. 3. Then 2 and finally 1. These numbers will be added to a result value to create the required reversed number 321. We can use the modulo operator, % to get the last digit of a number. 123%10 gives 3. Then we can convert 123 to 12 by changing it to the floor value of 123/10. On each step, we can append the last digit to the end of the final value to get the required reversed number.
The following algorithm can be used to reverse a number with a loop:
- Run a loop until the value of the number is greater than 0. Initialize one result variable as 0.
- On each step, use the modulo operator to find the last digit of the number.
- Multiply the result by 10 and add the calculated last digit to the multiplied value. It will keep adding the last digit to the end of the result value.
- Change the number to
floor(number/10). It will remove the last digit of the number.
The above steps will keep repeating till the number becomes 0. At the end of the program, the result variable will hold the required reversed value.
JavaScript program to reverse a number by using a while loop:
The following program uses the above algorithm to reverse a number with a while loop:
let rev = 0;
let num = 123456;
let lastDigit;
while(num != 0){
lastDigit = num % 10;
rev = rev * 10 + lastDigit;
num = Math.floor(num/10);
}
console.log("Reverse number : "+rev);Here,
- The variable
revis used to store the reversed value. It is initialized as 0. Thenumvariable is the given number and thelastDigitvariable is used to keep the last digit. - The
whileloop runs till the value ofnumis greater than 0. Inside the loop, we are calculating the last digit, appending it torevas the rightmost digit and removing the last digit from thenumvariable.
If you run this program, it will print the below output:
Reverse number : 654321Method 2: By converting the number to a string:
We can also do this in only one line. We need to convert the number to a string, split the string and put all characters of the string in an array, reverse the array, convert that array to a string by joining all characters and that string can be converted back to a Number.
We need to use the following methods here:
parseIntto parse the value as an integer.toStringto convert the number to a string.split()to split the characters of the string and add them to an arrayreverse()to reverse the arrayjoin()to join all characters to a string.
Below is the complete program:
let num = 123456;
let rev = parseInt(num.toString().split('').reverse().join(''));
console.log("Reverse number : "+rev);It will give a similar result.
Method 2(a): By using a separate function:
Let’s use a separate function to do the reversal.
function reverseNumber(num){
return parseInt(num.toString().split('').reverse().join(''));
}
let num = 768493;
let rev = reverseNumber(num);
console.log("Reverse number : "+rev);We created a new function reverseNumber that takes the number as its parameter and returns the reversed value. It will print:
Reverse number : 394867Method 2(b): Handling negative values:
The above methods will fail to handle negative numbers. For example, if you pass -123, it will print 321 as its reverse. Not -321. If you want to include negative numbers as well, you can multiply the result with the sign of the given number. The Math.sign method returns the sign.
function reverseNumber(num){
return parseInt(num.toString().split('').reverse().join('')) * Math.sign(num);
}
let num = -123;
let rev = reverseNumber(num);
console.log("Reverse number : "+rev);It will print -321.
Method 2(c): Handling float values:
We are not handling floating numbers in the above example. The parseInt method will parse the result as an integer. So, if we pass 123.45, it will return 54, not 54.321. To handle float values, we can use the parseFloat method instead of parseInt:
function reverseNumber(num){
return parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num);
}
let num = 123.45;
let rev = reverseNumber(num);
console.log("Reverse number : "+rev);It will work with both floating point numbers and negative numbers.
Reverse a user input number in HTML:
Let’s take the input from the user using HTML. We can execute JavaScript code from HTML. The JavaScript code is written inside the <script> block.
Create one file index.html with the below code snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
}
button {
background-color: #228ac2;
border: none;
color: white;
padding: 15px 15px;
text-decoration: none;
cursor: pointer;
border-radius: 12px;
width: 200px;
margin-top: 10px;
height: 30px;
line-height: 0;
}
</style>
<script>
function findReverse() {
let number = Number(document.getElementById("input_number").value);
let reverse = parseFloat(number.toString().split('').reverse().join('')) * Math.sign(number);
document.getElementById("result").innerHTML = reverse;
}
</script>
</head>
<body>
<h3>Reverse Number</h3>
<input id="input_number" />
<button onclick="findReverse()">Find Reverse</button>
<h4 id="result">-----</h4>
</body>
</html>If you open the .html file in a web browser, it will ask for a number as input from the user, and if you click on the button, it will show one alert with the reversed number.
- It has one
inputcomponent to take the user input. - Once the
buttonis clicked, it calls thefindReverseJavaScript method. - The
findReversemethod calculates the reversed value and assigns it to theresultcomponent.
You might also like:
- JavaScript program to read the current date time
- JavaScript program to find the sum of all even numbers below a given number
- JavaScript program to find the lcm of two numbers
- Different index related methods in JavaScript array
- How to change the text color in JavaScript on button click
- JavaScript program to find the volume of a sphere

