PDA

View Full Version : Rounding floating results

Piotto
11-09-2009, 02:45 PM
Hi everybody!

I am trying to add a rounding function inside the multiplication function Vic helped me to assemble. But is not working... I mean the multiplication works but the rounding not.
What i need is to round the multiplication results to 2 decimal even if the number is integer (like 100 i need to be 100.00).

The code....
[CODE]
<SCRIPT language = JavaScript>
<!--
function calculate2() {
var frm=document.catalogo1;
var a=frm.itemprice;
var b=frm.itemquantity;
var c=frm.subtotal;
for (var z0=0;z0<a.length;z0++){
c[z0].value=a[z0].value*b[z0].value;

//below here is not working
var newnumber = Math.round(c[z0].value*Math.pow(10,2))/Math.pow(10,2);
document.catalogo1.subtotal.value = newnumber;
}

}
//-->
</SCRIPT>
[CODE]

What i am doing wrong? :confused:

Alex Piotto

vwphillips
11-09-2009, 03:26 PM
<SCRIPT language = JavaScript>
function calculate2() {
var frm=document.catalogo1;
var a=frm.itemprice;
var b=frm.itemquantity;
var c=frm.subtotal;
// elements of the same name form an arry like collection
for (var z0=0;z0<a.length;z0++){
c[z0].value=Math.round(a[z0].value*b[z0].value);
}

}
</SCRIPT>

Piotto
11-09-2009, 03:38 PM
hi Vic and thanks again... It works... you are so fast! But I need to keep the two decimals after the dot, because of the currency around here. How to do it? With math.round or...?

jscheuer1
11-09-2009, 04:21 PM
Use:

c[z0].value=(a[z0].value*b[z0].value).toFixed(2);

c[z0].value=Math.round(a[z0].value*b[z0].value);

But perhaps you want to round to the nearest whole amount, or more likely (as in most currency transactions where rounding is involved) round up. To simply round, and ensure two decimal places:

c[z0].value=Math.round(a[z0].value*b[z0].value) + '.00';

To always round up:

c[z0].value=Math.ceil(a[z0].value*b[z0].value) + '.00';

Piotto
11-09-2009, 05:41 PM
Thanks Vic and Thanks Jonh. This was helpful and I will spend a time on the code to understand how it works.
regards
Alex :D