How to calculate currency appearing decimal places in JS?

4

I have a dynamic calculation to do, without having to click buttons. I even managed to, but the part I do not know is to make them appear as decimal places, since we're talking about currency.

function multiplica()
{
numer1 = parseInt(document.frmitementrada.quantidade.value);
numer2 = parseInt(document.frmitementrada.preuni.value);

soma = numer1 + numer2;

document.frmitementrada.total.value = soma;
}
<form name="frmitementrada" id="frmitementrada">
<td width="20%">

<INPUT TYPE="text" SIZE="3" NAME="quantidade" value="0">
<INPUT TYPE="text" onkeyup="multiplica()" SIZE="3" NAME="preuni"  value="0" >

<INPUT TYPE="text" SIZE="3" NAME="total">
</td>
</form>
    
asked by anonymous 22.01.2016 / 01:51

1 answer

5

Instead of parseInt() , use parseFloat() .

The parseInt transforms into integers, ie , without decimals. The parseFloat transforms into any operable number.

function multiplica()
{
numer1 = parseFloat(document.frmitementrada.quantidade.value);
numer2 = parseFloat(document.frmitementrada.preuni.value);

soma = numer1 + numer2;

document.frmitementrada.total.value = soma;
}
<form name="frmitementrada" id="frmitementrada">
<td width="20%">

<INPUT TYPE="text" SIZE="3" NAME="quantidade" value="0" />
<INPUT TYPE="text" onkeyup="multiplica()" SIZE="3" NAME="preuni"  value="0" />

<INPUT TYPE="text" SIZE="3" NAME="total" />
</td>
</form>

But remember that you will have to use dot . , instead of comma , , in the decimal places.

If you want to limit decimals, you can use .toFixed() , or .toPrecision() .

% with% limits the number of houses after the comma, while% with% limits the number of houses to the whole. In your case, using toFixed :

function multiplica()
{
numer1 = parseFloat(document.frmitementrada.quantidade.value);
numer2 = parseFloat(document.frmitementrada.preuni.value);

soma = numer1 + numer2;

document.frmitementrada.total.value = (soma.toFixed(2));
}
<form name="frmitementrada" id="frmitementrada">
<td width="20%">

<INPUT TYPE="text" SIZE="3" NAME="quantidade" value="0" />
<INPUT TYPE="text" onkeyup="multiplica()" SIZE="3" NAME="preuni"  value="0" />

<INPUT TYPE="text" SIZE="3" NAME="total" />
</td>
</form>
    
22.01.2016 / 01:59