We help IT Professionals succeed at work.

# Rounding to two decimal places

on
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){
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?
Comment
Watch Question

## View Solution Only

IT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:

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

function updateTotal2(){
with (document.forms){
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>
IT Expert
CERTIFIED EXPERT
Top Expert 2009
Commented:
That script will also return 2.50 instead of 2.5