www.webdeveloper.com
Results 1 to 5 of 5

Thread: rounding numbers

  1. #1
    Join Date
    Dec 2005
    Posts
    32

    rounding numbers

    Hello everyone,

    I have the following code:

    <html>
    <body>

    <script type="text/javascript">
    var result=Math.round(10.10123*100)/100 //returns 10.1
    alert(result)
    </script>

    </body>
    </html>

    This script alerts 10.1 and not 10.10

    Is there anyway to make it so that it rounds to two decimal places all the time?

    TYI

  2. #2
    Join Date
    Apr 2006
    Posts
    120
    var result=(Math.round(10.10123*100)/100).toFixed(2)

  3. #3
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,270
    Quote Originally Posted by yellabuff
    var result=(Math.round(10.10123*100)/100).toFixed(2)
    That can be shortened to Number.toFixed (2)
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  4. #4
    Join Date
    Jan 2005
    Location
    Los Angeles, CA
    Posts
    4,887
    Charles means:
    Code:
    var result=(10.10123).toFixed(2)
    The toFixed method will already round to the fixed digit after the decimal place and there is no need to do it twice. Also it should be noted that the toFixed method was added in Javascript 1.5 and older browsers like Safari and IE prior to 5.5 don't support it. Therefore you may want to define it for older browsers, but first test for it.

  5. #5
    Join Date
    Dec 2005
    Posts
    32
    Thank you. This worked.

Thread Information

Users Browsing this Thread

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

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