Tutorialspoint

How to remove the last digit of a number and execute the remaining digits in JavaScript?


1 Answer
vineeth.mariserla

Before the introduction of Bitwise operators, a number is first converted into a string and later on, using string methods, some part of that number is sliced and the remaining part is executed. Here type-conversion i.e a number into a string is necessary. But the introduction of Bitwise or has made the task very easy. When Bitwise or is used there is no necessity of type-conversion and there is no need of using any kind of string methods, reducing the effort and length of the code.

Example

In the following example, a string method called "string.substring()" is used to remove the last digit of a number.

Live Demo

<html>
<body>
<script>
   var str = '2345';
   document.write((str.substring(0, str.length - 1)));
</script>
</body>
</html>

Output

234

But after the advent of Bitwise or, the type conversion and string methods are nowhere in the picture. Bitwise or has made the code very concise.  

Example

Live Demo

<html>
<body>
<script>
   document.write(2345 / 10 | 0)
   document.write("</br>");
   document.write(2345 / 100 | 0)
   document.write("</br>");
   document.write(2345 / 1000 | 0)
</script>
</body>
</html>

Output

234
23
2

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.