JavaScript - El calculo lo hace mal al poner decimales

 
Vista:
Imágen de perfil de Eduardo
Val: 159
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

El calculo lo hace mal al poner decimales

Publicado por Eduardo (186 intervenciones) el 14/09/2024 17:34:46
Hola tengo este script el cual usa Javascript para adicionar casillas e ir calculando valores tipo factura. pero le puse una función a los campos para ir separando los valores por decimales ( así como se representan los valores) acá en Colombia son 3 decimales ejemplo 3.000 , 30.000 etc..

el ejemplo funciona perfecto si le quito los decimales (le quito igual la función para que no agregue el separador de decimales al ir escribiendo) y funcionan los cálculos bien.

el problema es cuando todo se hace con el separador de decimales los cálculos los hace mal y hasta no deja escribir cifras granes... POR QUEEEEE!!!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<form name="form1" method="post" action="enviacostos.php">
        <input name="id_servicio" type="hidden" id="id_servicio" value="<?php echo $id_servicio ?>" size="40">
        <input name="numero_servicio" type="hidden" id="numero_servicio" value="<?php echo $numero_servicio ?>" size="40">
        <input name="conducct" type="hidden" id="conducct" value="<?php echo $conductorgrua ?>" size="40">
        <div class="container" style="padding-left:25px">
          <div class="row clearfix">
            <div class="col-md-12">
              <table class="table table-bordered table-hover" id="tab_logic">
                <thead>
                </thead>
                <tbody>
                  <tr>
                    <td height="22"> </td>
                    <td>Producto</td>
                    <td>Cantidad</td>
                    <td>V. Unitario</td>
                    <td>V. Total</td>
                  </tr>
                  <tr id='addr0'>
                    <td>1</td>
                    <td><input type="text" name='product[]'  placeholder='' list='brow' class="form-control" />
                      <datalist id='brow'>
                        <option value='ACPM'>
                        <option value='COMIDA'>
                        <option value='HOTEL'>
                        <option value='OTROS'>
                      </datalist></td>
                    <td><input name='qty[]' type="number" class="form-control qty" placeholder='' min="0" step="0" value="1"/></td>
                    <td>
                    <!----<input type="number" name='price[]' placeholder='' class="form-control price" step="0" min="0" onKeyUp="format(this)" onChange="format(this)"/>--->
                   <input type="number" name='price[]' placeholder='' class="form-control price" onKeyUp="format(this)" onChange="format(this)"/>
                    </td>
                    <td><input type="number" name='total[]' placeholder='' class="form-control total" readonly/></td>
                  </tr>
                  <tr id='addr1'></tr>
                </tbody>
              </table>
            </div>
          </div>
          <div class="row clearfix">
            <div class="col-md-12" style="padding-left:19px; padding-top:10px;">
              <button type="button" id="add_row" class="btn btn-default pull-left" >+ Producto</button>
              <button type="button" id='delete_row' class="pull-right btn btn-default">- Producto</button>
            </div>
          </div>
          <div class="row clearfix" style="margin-top:20px">
            <div class="pull-right col-md-4">
              <table class="table table-bordered table-hover" id="tab_logic_total">
                <tbody>
                  <tr>
                    <th class="text-center">Total</th>
                    <td class="text-center"><input type="number" name='sub_total' placeholder='' class="form-control" id="sub_total" readonly/></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </form></td>
    </tr>
    <tr>
      <td height="15" bgcolor="#F0F1F2"> </td>
    </tr>
    <tr>
      <td height="15" bgcolor="#999999"> </td>
    </tr>
</table>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
function format(input)
{
var num = input.value.replace(/\./g,'');
if(!isNaN(num)){
num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1.');
num = num.split('').reverse().join('').replace(/^[\.]/,'');
input.value = num;
}
else{ alert('Solo se permiten numeros');
input.value = input.value.replace(/[^\d\.]*/g,'');
}
}
</script>
<script>
$(document).ready(function() {
  var i = 1;
 
  // Add
  $("#add_row").click(function() {
    b = i - 1;
    $('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
    $('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
    i++;
  });
 
  // Delete
  $("#delete_row").click(function() {
    if (i > 1) {
      $("#addr" + (i - 1)).html('');
      i--;
    }
    calc_total();
  });
 
  // On input value change
  $('#tab_logic tbody').on('input', 'input[type="number"]', function(evt) {
    calc($(evt.currentTarget).closest('tr'));
  });
 
  $('#tax').on('input', function() {
    calc_total();
  });
 
 
});
 
// Calcular total de la fila
function calc($tr) {
  var qty = $tr.find('.qty').val();
  var price = $tr.find('.price').val();
 
  // Total con 3 decimales
  $tr.find('.total').val((qty * price).toFixed(0));
 
  calc_total();
}
 
function calc_total() {
  var total = 0;
  $('#tab_logic .total').each(function() {
    // Obtener el valor como float
    total += parseFloat($(this).val());
  });
  // Dar formato con 3 decimales
  $('#sub_total').val(total.toFixed(0));
 
  // Esto podría estar en otra función
  tax_sum = total / 100 * $('#tax').val();
  $('#tax_amount').val(tax_sum.toFixed(0));
  $('#total_amount').val((tax_sum + total).toFixed(0));
}
</script>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder