Problems with calculations in Javascript

Asked

Viewed 971 times

3

Well I edited the question, because I located the problem. I have a javascript responsible for making calculations with the values in the input, and I have a plugin Jquery Mask or Maskmoney to make the formatting of the entered value.

Both plugins have the same error.

Jquery Mask - When I type 1,00 the javascript that makes the calculation takes the value 100.

Maskmoney - When I type something, the javascript that makes the calculation thinks the field is empty.

I need to help, I thank you already

Follows the code:

$(document).ready(function() {
  $(".valor").on("input", function() {

    // Margem
    var valor = $(this).val();
    valor = valor.replace(".", "");
    valor = valor.replace(",", ".");

    // Custo
    var valorCusto = $("#custo").val();
    valorCusto = valorCusto.replace(".", "");
    valorCusto = valorCusto.replace(",", ".");


    var calculo = (parseFloat(valor) - parseFloat(valorCusto)) / parseFloat(valorCusto) * 100;
    var inputMargem = $(this).attr("margem");
    var resultadoMonetario = calculo.toFixed(2).replace(".", ",");
    $("#" + inputMargem).val(resultadoMonetario);
  });

  $(".margem").on("input", function() {

    // Margem
    var valorMargem = $(this).val();
    valorMargem = valorMargem.replace(".", "");
    valorMargem = valorMargem.replace(",", ".");

    // Custo
    var valorCusto = $("#custo").val();
    valorCusto = valorCusto.replace(".", "");
    valorCusto = valorCusto.replace(",", ".");


    var calculo = (parseFloat(valorCusto) * parseFloat(valorMargem) / 100) + parseFloat(valorCusto);
    var inputValor = $(this).attr("valor");
    var resultadoMonetario = calculo.toFixed(2).replace(".", ",");
    $("#" + inputValor).val(resultadoMonetario);
  });
});

$('.valores').mask('00.000.000,00', {
        reverse: true
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.js"></script>


Custo:
<input type='text' id='custo' class='custo valores' name='custo'>
<br>
<br> Valor:
<input type='text' id='valor1' class='valor valores' name='valor1' margem='margem1'> Margem:
<input type='text' id='margem1' class='margem valores' name='margem1' valor="valor1">

<br> Valor:
<input type='text' id='valor2' class='valor valores' name='valor2' margem='margem2'> Margem:
<input type='text' id='margem2' class='margem valores' name='margem2' valor="valor2">

the strange and that here in the stack it works. Example:

1st cost = 5,55 2nd margin = 1,00 Result = 5,61

Already the same problem code on my page and here:

JSFIDDLE

  • Hugo, not to be a dick to you, but if you used Mask-money you wouldn’t have any of these problems you’re encountering. As I told you in another answer, working with values is much more than recommended, including by the jQuery Mask community. I’m sorry to insist, but from my point of view, you’re wasting time on something you wouldn’t need.

  • This conversion you need to do, the plugin itself has by default, as I answered in your other question

  • Pedro I tried to use with maskmoney and this giving problem, look at https://jsfiddle.net/7aq46h0x/12/ I realized that with maskMoney when I type a value and as if the input was empty, and for Mask and as if it had no commas. The problem is this

  • https://jsfiddle.net/7aq46h0x/18/

  • Nice, but the only problem and that needs to go out of input to do the calculation, has how to change this to the calculation to be done in real time?

  • Dude, I already gave you a ready answer, which is not the point of Stackoverflow. How about trying to understand what you’re doing? Take a look at this one link. Excuse the rudeness, but a minimum of effort is valid, do not think?

  • yes I fully agree

Show 2 more comments

2 answers

2

you need to replace the dots and commas, follows an example:

// instancie o objeto intl apenas uma vez.
var intl = new Intl.NumberFormat("pt-BR", {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});

var valor = {};
valor.text = "12.345.678,90";
valor.float = parseFloat(valor.text.replace(/[.]/gi, "").replace(",", "."));
valor.format = intl.format(valor.float)

console.log(intl, valor);

script change:

$(function () {
    var intl = new Intl.NumberFormat("pt-BR", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });

    var parseFloatIntl = function (value) {
        value = value.replace(/[.]/g, "").replace(",", ".")
        value = parseFloat(value) || 0;
        return value;
    }

    var input = {};
    input.custo = $('#custo');
    input.valor = $('.valor');
    input.margem = $('.margem');
    input.inputs = $('input');      

    input.valor.on("input", function () {
        var self = $(this);
        var inputMargem = $("#" + self.attr("margem"));

        var valor = {};
        valor.Margem = parseFloatIntl(self.val());        
        valor.Custo = parseFloatIntl(input.custo.val()); 
        valor.Calculo = (valor.Margem - valor.Custo) / valor.Custo * 100;

        inputMargem.val(intl.format(valor.Calculo));
        inputMargem.trigger('blur');
    });

    input.margem.on("input", function () {
        var self = $(this);
        var inputValor = $("#" + self.attr("valor"));

        var valor = {};
        var valor.Margem = parseFloatIntl(self.val()); 
        var valor.Custo = parseFloatIntl(input.custo.val());        
        var valor.Calculo = (valor.Custo * valor.Margem / 100) + valor.Custo;        

        inputValor.val(intl.format(valor.Calculo))
        inputValor.trigger('blur');
    });

    input.inputs.mask('00.000.000,00', {
        reverse: true
    });
});
  • ok and then how do I convert it to be written at 3.333,33? for what I saw with that then I will convert it to 3333.33.

  • @Hugoborges, if you want to format the number for the regional format (in the case of Brazil, the thousand separator is the . and the decimal to ,), you must use the Intl.NumberFormat(locale)

  • I understand, look I edited my question, I’m not able to tidy up, have you pick up and make the change in my java, and post as answer?

  • I made a change, maybe you’ll have to make some adjustments.

  • got it, but it’s not working, I made some changes but it didn’t work. I’m not very good with javascript hahahahah

  • 1

    @Hugoborges, try to debug your code, Devtools to Chrome/Opera is great for this.

  • I noticed that the problem occurs with the mask, for some reason when I type 1.00 and as if I had 100 in the input. look at https://jsfiddle.net/7aq46h0x/11/

Show 2 more comments

2


Try it like this:

$(document).ready(function () {
$(".valor").on("input", function () {
    // Margem
    var valor = $(this).val();
    var valorCorrigido = parseFloat(adicionarPontos(valor));

    var valorFloat = parseFloat(valorCorrigido) || 0.0;

    // Custo  
    var valorCusto = $('#custo').val();
    var valorCustoCorrigido = parseFloat(removerPontos(valorCusto));
    var valorCustoFloat = parseFloat(valorCustoCorrigido) || 0.0;

    // Calculo
    var calculo = (parseFloat(valorFloat) - parseFloat(valorCustoFloat)) / parseFloat(valorCustoFloat) * 100;
    var inputMargem = $(this).attr("margem");

    $("#" + inputMargem).val(calculo.toFixed(2)).trigger('blur');
});
// Faz o calculo do valor com base na margem
$(".margem").on("input", function () {
    // Margem
    var valorMargem = $(this).val();  
    var valorMargemCorrigido = parseFloat(adicionarPontos(valorMargem));
    var valorMargemFloat = parseFloat(valorMargemCorrigido) || 0.0; 

    // Custo
    var valorCusto = $('#custo').val();
    var valorCustoCorrigido = parseFloat(removerPontos(valorCusto));
    var valorCustoFloat = parseFloat(valorCustoCorrigido) || 0.0; 

    // Cálculo
    var calculo = (parseFloat(valorCustoFloat) * parseFloat(valorMargemFloat) / 100) + parseFloat(valorCustoFloat);
    var inputValor = $(this).attr("valor");

    var resultadoMonetario = calculo.toFixed(2).toString();
    resultadoMonetario = resultadoMonetario.replace(".", ",");

    $("#" + inputValor).val(resultadoMonetario).trigger('blur');
});

function removerPontos(valor){
    valor = valor.replace(".","");
    valor = valor.replace(",",".");
    return valor;           
}

function adicionarPontos(valor){
   if(valor.length == 1){
       return valor;
   }
   else{
   if(valor.length == 2){
       return valor;
   }
   else{
   valor = valor.replace(",","");
     var inteiro = valor.substring(0,valor.length - 2);

   console.log(inteiro);

   var decimal = valor.substr(2);

   console.log(inteiro + "." + decimal);
   return inteiro + "." + decimal;
   }
   }
}
});

$('input').mask('00.000.000,00', {
    reverse: true
});
  • went wrong, I edited the question explaining better the problem, look if you will understand why I do not know if I explained right hahahah

  • I updated the answer.

  • hahahah, check out:https://jsfiddle.net/7aq46h0x/14/

  • I missed a detail I got right

  • keeps miscalculating look only: https://jsfiddle.net/7aq46h0x/22/ The problem and when I type 1.00 the java thinks I typed 100. Very strange

  • 1

    https://jsfiddle.net/7aq46h0x/30/

  • Friend I have no words to thank. Thank you very much. I’m taking a look here and seeing everything you changed. The only thing I noticed is that the . still of the problem. But I think no one will use 1,000.00 in the margin ;)

Show 2 more comments

Browser other questions tagged

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