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
https://forums.phpfreaks.com/topic/61411-solved-rounding-numbers/
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>

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.

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>

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?

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));
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.