Web Analytics Made Easy -
StatCounter really confused!! - CodingForum

Announcement

Collapse
No announcement yet.

really confused!!

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • really confused!!

    var n = 123456.789;
    n.toFixed(0);


    just starting out JavaScript. So i type the above code in firebug. it returns this result:- "123457"
    As for as i know, toFixed() converts a number to a string with a specified number of digits after the decimal point.

    If i have specified 0, which i'm assuming it means 0 digits after the decimal point, why does the 7 appear and the 6 is taken out.

    really fustrating and can't seem to get my head over it.

  • #2
    The toFixed() method formats a number to use a specified number of trailing decimals.

    The number is rounded up, and nulls are added after the decimal point (if needed), to create the desired decimal length.

    from w3schools

    google is your friend

    Comment


    • #3
      To verify the effects of the rounding, try:
      Code:
      var n = 123456.789;
      n.toFixed(1);

      Comment


      • #4
        just to verify, JS rounds only if that number if 5 or above depending on what value you input to the toFixed() method
        Last edited by laylo; Sep 11, 2011, 04:08 AM.

        Comment


        • #5
          Originally posted by laylo View Post
          just to verify, JS rounds only if that number if 5 or above depending on what value you input to the toFixed() method
          Yes, whether that is a statement or a question.

          Comment


          • #6
            well, to be finicky it always rounds - but whether it rounds up or down depends on the last decimal it looks at.

            if you want to keep your number and just get rid of the decimals you can use parseInt:

            Code:
            var n = 123456.789;
            y=parseInt(n);
            alert("Int= "+y);

            Comment


            • #7
              To NOT round, you could:
              Code:
              <script type="text/javascript">
              var n = 123456.789;
              n = parseInt(n*10)/10
              alert(n);
              
              n = 2/3;
              n = parseInt(n*100)/100;
              alert(n);
              </script>

              Comment

              Working...
              X
              😀
              🥰
              🤢
              😎
              😡
              👍
              👎