www.webdeveloper.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2012
    Posts
    1

    Infinity problem

    hello
    i simply want to reverse the digits of a number using java script but m not getting correct output.

    <html>
    <head>
    <title>demo1</title>
    <script language="javascript">
    var n = null;
    var r,rev=0;
    n = parseInt(window.prompt("Enter number"));

    while(n>0)
    {
    r = n % 10;
    rev = rev *10 +r;
    n = n/10;
    }
    alert(rev);
    </script>
    </html>

    result is coming out to be infinity..
    plz help me out
    Thanks in advance.

  2. #2
    Join Date
    Feb 2006
    Posts
    2,925
    Simplest to forget about numbers and modulus.
    A prompt returns a string, just reverse the string.
    Code:
    var n=window.prompt("Enter number");
    alert(n+' reversed= '+n.split('').reverse().join(''));

  3. #3
    Join Date
    Jan 2012
    Location
    United States
    Posts
    15
    Hello shwetab,

    The problem is that in JavaScript (unlike C or Java), just because the operands of the / operator are both integers, doesn't mean that the value returned will be an integer. Rather, if the result of the division has a fraction part, JavaScript returns the exact value as a real number. This can be fixed by using the Math.floor() method to keep 'n' an integer value:
    Code:
    <script language="javascript">
    var n = null;
    var r,rev=0;
    n = parseInt(window.prompt("Enter number"));
    
    while(n>0)
    {
    r = n &#37; 10;
    rev = rev *10 +r;
    n = Math.floor (n/10);
    }
    alert(rev);
    </script>
    Last edited by mjy; 02-01-2012 at 09:24 PM.
    Author of the Kindle book JavaScript : Just the Basics - A Primer for the Complete Beginner. Learn JavaScript for the price of a fancy coffee drink.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles