Solved

Rounding numbers to two decimals

Posted on 1998-11-30
6
516 Views
Last Modified: 2008-03-17
In the following Script; how do I get the total to round to two decimal places i.e. $21.36?

<html>
<head>
<script language="JavaScript">
var N=3 // number of VAL/QTY  pairs

function calcit()
      {
      stotal = 0;
      f = document.forms[0];
      for(i=0 ; i<N ; i++)
            {
            if (f.elements[i*2].value >= 0)
                  {
                  v = f.elements[i*2].value;
                  q = f.elements[i*2+1].value;
                  t1 = v * q;
                  }
                  stotal += t1;
                  }
                  f.stotal.value = "$" + stotal;

      //10%tax
      total = stotal * 1.0775;
      f.total.value = "$" + total;
}
</script>
</HEAD>

<BODY>
<FORM>
VAL1:<INPUT TYPE="text" name="v1" value="" size=6><br>
QTY:<INPUT TYPE="text" name="q1" value="1" size=3><br>

VAL2:<INPUT TYPE="text" name="v2" value="" size=6><br>
QTY:<INPUT TYPE="text" name="q2" value="1" size=3><br>

VAL3:<INPUT TYPE="text" name="v3" value="" size=6><br>
QTY:<INPUT TYPE="text" name="q2" value="1" size=3><br>

STOTAL:<input name="stotal" type='text'>
TOTAL:<input name="total" type='text'>
<input type="submit" value="calculate" onClick="calcit();return false;">
</FORM>
</BODY>
</html>
0
Comment
Question by:timothy1
  • 4
6 Comments
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 50 total points
Comment Utility
This one is from Netscape:
<html>
<head><title>Round off Long numbers</title>
<script>
function roundOff(value, precision)
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}
</script>
</head>

<body>
<h3><center>Testing Rounding off Long floating point
numbers</center></h3>
<form name=myForm>
<pre>
Enter a long number <input type=text name=text1
value=5.199999999999999999 size=20>
Enter precision     <input type=text name=text2 value=2 size=2>
Result              <input type=text name=text3>
</pre>
<center>
<input type=button value=Calculate onClick="myForm.text3.value =
roundOff(myForm.text1.value, myForm.text2.value)">
</center>
</form>
</body>
</html>
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
So in your case it would be

f.total.value = "$" + roundOff(total, 2);
f.stotal.value = "$" + roundOff(stotal, 2);

Michel
0
 
LVL 10

Expert Comment

by:kollegov
Comment Utility
mplungjan, Do you EVER check your posts?
Try to roundOff(0.11,2) with script you suggested
you will get 11 instead of 0.11

timothy1, this is bugs free solution. (TESTED)
Hope this one is better than above buggy solution
from developer.netscape.com

function roundOff(total,prec)
{total=""+Math.round(total*Math.pow(10,prec));
 inx=total.indexOf(".")
 if(inx!=-1) total=total.substring(0,inx);
 while(total.length<prec) total="0"+total;
 alert(total)
 total=total.substring(0,total.length-prec)+"."+total.substring(total.length-prec);
 return total;
}

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Hey, hey, kollegov - that comment was uncalled for...
I check 99.9% of my answers.

In this case I cut and pasted a script from netscape and I really expected to work without even thinking it might be wrong. I am at home on a crap pc so I skipped testing for once.

Timothy: I am sorry if the script did not work. Feel free to reject my answer and if kolloegovs script works better, let him answer instead. I would normally give you one of my (tested) scripts, but they are not on my home pc. I apologise.

Michel
0
 

Author Comment

by:timothy1
Comment Utility
Well guys don't fight! I put the first one in my Html (after taking out just the script) and sent the roundoff() function various prices. It worked fine. The object was to use it in an order form, so the user wouldn't get the math wrong when figuring the sales tax (or sub-totals). I doubt if the customer will have prices that after taxes will end up with 0.11 it works fine with 20.101 and the like.

I will try the other one also, but I think the first will fit the need I haven't taken Java yet only "C", but as you know they seem to be similiar in syntax and grammer.

Interestingly enough, you mentioned this came from Netscape?
I ran it through IE4 and it worked fine.

You don't happen to know of a online reference or tutorial that list all those math.round(), math.pow(), parseInt(), etc. functions that I see in the code and tells what they are for?
I can guess at most, but a list would be cool!

I'll check out that URl,,,,developer.netscape.com

Again Thanks,
Tim
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Thanks. Netscape and Microsofts core javascript works 99.99999999997 % the same ;-).

http://developer.netscape.com/ also has the javascript reference
It seems the site is down for maintenance so I cannot give you the exact URL of the math stuff.
Javascript syntax looks a lot like java especially in the math package.
Math.round rounds down to the nearest integer
Math.pow(x,y) will compute x to the power of y - may cause overflow for large values of y
for IEs look at http://msdn.microsoft.com/scripting/
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now