How to calculate currency by appearing decimal places in JS?

Asked

Viewed 1,993 times

4

I have a dynamic calculation to do, without having to click buttons. I did, but the part I don’t know how to make it appear like 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>

1 answer

5


Instead of parseInt(), use parseFloat().

The parseInt transforms into whole numbers, that is, without decimals. Already 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 have to use stitch ., instead of a comma ,, to the decimal places.

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

The toFixed, limits the number of boxes after the comma, already the toPrecision limits the house number altogether. In your case, using the 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>

  • Could I send to total with two decimal places to the right? and at most 3 to the left?

  • 1

    @Would have yes, I will edit the answer with your question...

  • beauty I’ll be waiting.

  • 1

    @Ezer, look at the issue. If you have in mind something more complex, like a mask, you better look at another answer here from Sopt, there are several about that. Or ask a new question. Since this was just about that.

  • show thanks even now I leave for mask I have a scheme here I will adapt. I needed to better understand how it worked thanks.

  • @Ezer, you’re welcome :)

  • deserved even a bonus! Congratulations!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.