-1

I have a javascript to calculate taxes and it works like this

The html form

 <td><input type="text" class="input-180" name="pbruto" id="pbruto" value="0"/></td>
    <td><input type="text" class="input-180" name="pneto" id="pneto" value="0"></td>
    <td><input type="text" class="input-180" name="piva" id="piva" value="0"></td>

The javascript code

<script>
var taxPerc = 1.19; 
document.getElementById("pbruto")
.onkeyup = function(){
document.getElementById("pneto")
.value = parseFloat(document.getElementById("pbruto")
.value) * (1.00 / taxPerc)
document.getElementById("piva")
.value = parseFloat(document.getElementById("pbruto")
.value) - parseFloat(document.getElementById("pneto").value)
}
</script>

The problem is that the results I get from calculations are displayed like this

8403.361344537816

I need to get rid of those .361344537816 and format the number to 8.403 only

Any way to do this?

EDIT No solutions yet

2 Answers2

0

Lets say var x is holding the value, try:

x = parseInt(x) / 1000
Amir Yahalom
  • 156
  • 2
0

It's easier to control the code, if you'd use variables instead of DOM to store values. I've re-written your code, and toLocaleString() method seems to do exactly what you want:

var taxPerc = 1.19;
document.getElementById("pbruto").addEventListener('input', function () {
    var valNeto, valPiva,
     elNeto = document.getElementById("pneto"),
     elBruto = document.getElementById("pbruto"),
        elPiva = document.getElementById("piva"),
        valBruto = +(elBruto.value);

    valNeto = valBruto * (1 / taxPerc);
    valPiva = valBruto - valNeto;
    elNeto.value = Math.round(valNeto).toLocaleString('de-DE');
    elPiva.value = Math.round(valPiva).toLocaleString('de-DE');
});
label {
    display: block;
}
<label>Bruto: <input id="pbruto" /></label>
<label>Neto: <input id="pneto" /></label>
<label>Piva: <input id="piva" /></label>
Teemu
  • 22,918
  • 7
  • 53
  • 106