Jump to content

[SOLVED] Rounding numbers


hostfreak

Recommended Posts

Hello, I am trying to figure out how to implement the Math.round() function into the following:

 

function calculate_a()
{
    var elems = document.forms['work_order'].elements;
    var total_a = 0;
    for (var i = 0; i < elems.length; i++)
    {
        if (elems[i].name.indexOf('number_a') !=-1)
        {
            total_a += +(elems[i].value);
        }
    }
    elems['totals_a'].value = total_a;
}

 

I want to round the number to two decimals; Math.round(field*100)/100 . However, I am unsure how to implement it into the above. Thanks in advanced.

Link to comment
Share on other sites

hummmm, something is odd about this addition since 21.15+60.80 = 81.95 without any rounding up.

 

The rounding script works as is, you can try this to see how it works.

<input type="text" name="txt" id="txt" />
<script language="javascript">
document.getElementById('txt').value = Math.round(81.94999999999999*100)/100;
</script>

Link to comment
Share on other sites

hummmm, something is odd about this addition since 21.15+60.80 = 81.95 without any rounding up.

 

For humans this is true, but for computers it's not always the case.  The problem arises in that there are a limited number of bits to represent any value in a computer but there are infinite floating point numbers.

 

For example, there are infinite values between 0.00001 and 0.00002.  However, most computers only have 32 or 64 bits to represent all of those possible values.  Thus, floating point numbers in computers are almost always approximations to their real values and you can almost never count on them being exact.

 

Taking our example from this thread, if we do:

21.15 + 60.80 = 81.95

it is fairly straight-forward.

 

However, if we try the following in a computer:

if( (21.15 + 60.80) == 81.95 ){
  alert("true");
}

We may not see an alert box!  This is because either of the two operands may be an approximation to the real value, which means the computer might actually be performing:

21.149999999999999 + 60.79999999999999

or something similar.

 

If you want to use floating point numbers in comparisons that are not equivalent to integers (i.e. numbers that are not equivalent to 0.00, 1.00, 2.00), you might have to do something like this:

var aFloat = 21.15 + 60.80;
if( aFloat >= 81.94 && aFloat <= 81.96 ){
  alert("true");
}

You can change the values 81.94 and 81.96 to be more precise if necessary.

 

The thing to remember is that when performing floating point calculations you are almost always dealing with approximations and not exact numbers.

Link to comment
Share on other sites

I wrote a quick my_round function that seems to work fairly well.

 

<html>
  <head>
    <title>Javascript Round Function</title>
    <script type="text/javascript">
      function my_round(num, dec){
        dec = dec === undefined ? 2 : dec;
        if(typeof num == "number" &&
           typeof dec == "number"){
          return num.toFixed(dec);
        }
        return Number.NaN;
      }
    </script>
  </head>
  <body>
    <script type="text/javascript">
      alert(my_round(5));
      alert(my_round(21.15, 7));
      alert(my_round(60.80, 10));
      alert(my_round(21.15 + 60.80,);
    </script>
  </body>
</html>

Link to comment
Share on other sites

I'm not sure if the objective of my script is clear, of if I failed to make it clear, if so I apologize. I am sure my inability to comprehend how to implement your function in my script comes from my ignorance with Javascript.

 

My script, is supposed to take a number of input fields (of whom will each contain one price; field 1: 21.15,  field 2: 60.80 etc), with the "onchange" of calculate_a. The script is supposed to take all the prices, add them together and output them to an input field (of whom has a name of 'totals_a'). It does that fine, unless of course when adding certain prices together, which results in what is shown in my example provided above.

 

So with that said, how would your function implement into my script, to get the desired result?

Link to comment
Share on other sites

function my_round(num, dec){
  dec = dec === undefined ? 2 : dec;
  if(typeof num == "number" &&
   typeof dec == "number"){
     return num.toFixed(dec);
   }
  return Number.NaN;
}

function calculate_a()
{
    var elems = document.forms['work_order'].elements;
    var total_a = 0;
    for (var i = 0; i < elems.length; i++)
    {
        if (elems[i].name.indexOf('number_a') !=-1)
        {
            total_a += +(elems[i].value);
        }
    }
    elems['totals_a'].value = my_round(new Number(total_a));
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.