Link to home
Start Free TrialLog in
Avatar of Rotigel
Rotigel

asked on

Rounding to two decimal places

I am trying to round a calculated number in a form field to two decimal places.  

The form field's name is 'crcont', and its value is determined by the code below:  


<script language="javascript">
<!--

function updateTotal2(){
with (document.forms[0]){
 crcont.value = parseFloat(crbiweekly.value) * parseFloat(crppd.value) + parseFloat(crcamount.value);
}    
}

//-->
</script>


Where do I put the code below, and what should I replace the 'num' in the code with?


function round(num) {
     return Math.round(num * 100) / 100;
}

Or is there an easier way?
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image



<script language="javascript"><!--

function updateTotal2(){
   with (document.forms[0]){
      crcont.value = twoDecimals(parseFloat(crbiweekly.value) *
       parseFloat(crppd.value) +
       parseFloat(crcamount.value));
   }    
}



function twoDecimals(n) {
   var s = "" + Math.round(n * 100) / 100
   var i = s.indexOf('.')
   if (i < 0) return s + ".00"
   var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
   if (i + 2 == s.length) t += "0"
   return t
}

</script>
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial