Reversing Numbers in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript(("JavaScript")) -.-> javascript/AdvancedConceptsGroup(["Advanced Concepts"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("Template Literals") subgraph Lab Skills javascript/variables -.-> lab-28599{{"Reversing Numbers in JavaScript"}} javascript/data_types -.-> lab-28599{{"Reversing Numbers in JavaScript"}} javascript/arith_ops -.-> lab-28599{{"Reversing Numbers in JavaScript"}} javascript/comp_ops -.-> lab-28599{{"Reversing Numbers in JavaScript"}} javascript/template_lit -.-> lab-28599{{"Reversing Numbers in JavaScript"}} end

Reversing a Number

To reverse a number using JavaScript, you can use the reverseNumber() function with the following steps:

  1. Convert the number n to a string using Object.prototype.toString().
  2. Use String.prototype.split(), Array.prototype.reverse() and Array.prototype.join() to get the reversed value of n as a string.
  3. Convert the string back to a number using parseFloat().
  4. 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.