# Thread: need help in rounding off into two decimal places

#### Hybrid View

1. Registered User
Join Date
Oct 2011
Posts
357

## need help in rounding off into two decimal places

Hi..

I have javascript code with computation, but I have problem in my result because it was not round off or fixed into two decimal places only.

here is my code:

Code:
```<script type="text/javascript">

function test_(cmpd) {
var len_ = (document.frmMain.elements.length) - 1;

for (i=0; i <= len_; i++ ) {

var strPos_ = document.frmMain.elements[i].id.indexOf(cmpd)

if (strPos_ != -1) {
var strPos = document.frmMain.elements[i].id.indexOf("_");

var strId = document.frmMain.elements[i].id.slice(strPos + 1) + "_" + document.frmMain.elements[i].id.slice(0,strPos)
// this is the computation that I need to fixed the result into two decimal places
document.frmMain.elements[i].value = document.getElementById(strId).value * document.getElementById('mult').value;
}
}
}
</script>```
Thank you so much

2. Registered User
Join Date
Aug 2010
Location
San Diego
Posts
244
A simple function like so will round n to 2 decimal places:
Code:
```
function rnd(n) {
return Math.round(n * 100) / 100;
}```
Last edited by handcraftedweb; 05-02-2012 at 10:21 PM.

3. Registered User
Join Date
Oct 2011
Posts
357
I tried it, but on the first iitem it works correctly, but on the second Item it did not work the result from 10 * .92 = 9.2 but the result from my code is 920

Code:
```<script type="text/javascript">

function test_(cmpd) {
var len_ = (document.frmMain.elements.length) - 1;

for (i=0; i <= len_; i++ ) {

//var count_ = len_;
//var dash_ = count_.count('-');
var strPos_ = document.frmMain.elements[i].id.indexOf(cmpd)

//if (document.frmMain.elements[i].id.substr(2,3) == cmpd ) {
if (strPos_ != -1) {
var strPos = document.frmMain.elements[i].id.indexOf("_");

var strId = document.frmMain.elements[i].id.slice(strPos + 1) + "_" + document.frmMain.elements[i].id.slice(0,strPos)
// document.frmMain.elements[i].value = document.getElementById(strId).value * document.getElementById('mult').value;
document.frmMain.elements[i].value = Math.round((document.getElementById(strId).value * document.getElementById('DemandedQty').value) * 100 ) / 100;
}
}
}
</script>```
Thank you

4. Registered User
Join Date
Aug 2010
Location
San Diego
Posts
244
Sorry, try this
Code:
```function rnd(n) {
return n.toFixed (2);
}```
or
Code:
`    document.frmMain.elements[i].value = (document.getElementById(strId).value * document.getElementById('DemandedQty').value).toFixed (2);`

5. Registered User
Join Date
Oct 2011
Posts
357
Originally Posted by handcraftedweb
Sorry, try this
Code:
```function rnd(n) {
return n.toFixed (2);
}```
or
Code:
`    document.frmMain.elements[i].value = (document.getElementById(strId).value * document.getElementById('DemandedQty').value).toFixed (2);`

Thank you