...

View Full Version : Round number 2 decimal points

mbarandao
12-06-2010, 07:21 PM
Hello:

I have this js function:

<script type="text/javascript">
document.PaymentForm.newbalance.value = (document.PaymentForm.balance.value -0) - (document.PaymentForm.paymentamount.value -0);
}
</script>

I want to round the value of
document.PaymentForm.newbalance.value
to two decimal points.

May I request some assistance!

barkermn01
12-06-2010, 07:26 PM
toFixed(2)

var textValue = document.PaymentForm.newbalance.value;
var floatValue = parseFloat(textValue);

var formatedFloat = floatValue.toFixed(2)

mbarandao
12-06-2010, 07:31 PM
Much oblige!

Philip M
12-06-2010, 10:37 PM
toFixed() returns a string value, so if the number is to be subject to further calculation either it must be converted back to a number with Number or parseFloat(), or the following method used to round to 2DP.

<script type = "text/javascript">

function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

alert (roundNumber (12345.6789, 2));
</script>

mbarandao
12-07-2010, 03:20 AM
Thanks Philip M for further explaining the toFixed().

If my function that performs the calculation is this:

<script type="text/javascript">
document.PaymentForm.newbalance.value = (document.PaymentForm.balance.value -0) - (document.PaymentForm.paymentamount.value -0);
}
</script>

How do I incorporate your suggested function

<script type = "text/javascript">

function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}

alert (roundNumber (12345.6789, 2));
</script>

into one to thus do the calculation and round the number?

Philip M
12-07-2010, 07:28 AM
<script type="text/javascript">
var bal = document.PaymentForm.balance.value - document.PaymentForm.paymentamount.value;
bal = Math.round(bal*Math.pow(10,2))/Math.pow(10,2);
document.PaymentForm.newbalance.value = bal;
}
</script>

mbarandao
12-07-2010, 08:19 AM
Man, such a headache you have saved me from. Thank you sir!

I'm quite new to js--and still learning

Again, Thanks!
Mossa

Philip M
12-07-2010, 08:39 AM
Rounding 12345.00 or 12345 to 2 decimal places will result in 12345 which may not be what you want.

You should use toFixed() for display purposes but the code given for calculation purposes. So perhaps you need both forms:-

<script type="text/javascript">
var bal = document.PaymentForm.balance.value - document.PaymentForm.paymentamount.value;
var calcBal = Math.round(bal*Math.pow(10,2))/Math.pow(10,2); // the value for calculations
var displayBal = bal.toFixed(2); // the value to be displayed
document.PaymentForm.newbalance.value = displayBal;
}
</script>

mbarandao
12-07-2010, 08:59 AM
Great thought! I did in fact reproduce a similar condition during testing. This secondary suggestion perhaps addresses this.

Again, thank you kindly!
Mossa

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum