Calculus in Javascript

Asked

Viewed 944 times

2

I have two input fields where I type values. I put mask so that when type the value is in the format 0,00. How do I make a simple calculation with values 0.00? Because I have a formula that I passed and that the result, either from 0 or appears Nan. Follows the code of the formula, of the calculation.

$(function(){
    $("#precoVendaNoMercado, #descPromo , #descFinan ").change (function(){
        if($("#precoVendaNoMercado").val() != "" && $("#descPromo").val() != "" && $("#descFinan").val() != "") {
            precoDeVendaRealizado = parseFloat($("#precoVendaNoMercado").val() * (1- (parseFloat($("#precoVendaNoMercado").val())) + parseFloat($("#precoVendaNoMercado").val())) / 100 );
            console.log('Calculo:'+precoDeVendaRealizado);
        }
    });
});

I did what you suggested @Diego Souza. And on Chrome console points to the line:

var desFinan = descFinan.replace('.', '').replace(',', '.'); precoDeVendaRealizado = precoVeNoMerc * (1 - (desPromo + desFinan) / 100 ); 

Saying "Uncaught Typeerror: Cannot read Property 'replace' of Undefined"

  • you’re always counting the $("#precoVendaNoMercado").val(), is correct? It shouldn’t be: precoDeVendaRealizado = parseFloat($("#precoVendaNoMercado").val() * (1- (parseFloat($("#descPromo").val())) + parseFloat($("#descFinan").val())) / 100 );

  • Can you give examples of values you have? The mask also adds points?

  • @Sergio, I’m turning my data into float, with parseFloat, but when we are penny values, the result does not appear with that penny, example: 1,11 + 1,11 the result is only 2 and not 2,22. After converting the data into float, I do the following: variavel1 + variavel2, it is wrong?

3 answers

2


You must replace "," with "." or convert the values to float:

var valorConvertido = parseFloat($("#precoVendaNoMercado").val());
  • Thanks @ Kayo Bruno. E how do I then display the result in the 0.00 format?

  • Gives a replace by replacing ''." with ",".

  • I am turning my data into a float, with parseFloat, but when we are pennies, the result does not appear with that penny, example: 1,11 + 1,11 the result is only 2 and not 2,22. After converting the data into float, I do the following: variavel1 + variavel2, it is wrong?

2

Remove all points and commas from the string making it whole, then divide by a hundred, bringing the decimal places in numerical form.

jQuery(document).ready(function($){
    $("#go").click(function(event){
        event.preventDefault();
        if(
          $("#precoVendaNoMercado").val() != "" && 
          $("#descPromo").val() != "" && 
          $("#descFinan").val() != ""
        ) {
          // Trabalhe com uma variável, é sempre melhor
          var valor = $("#precoVendaNoMercado").val();
            
          if (valor.indexOf(",") == -1) { // verifica se tem casas decimais
             valor += ",00"; // Se não tiver coloca
             var dec = 2; // Duas casas decimais
             var ndec = 100; // 100 para duas casas decimais (10 para 1, 1000 para 3)
              
            } else {
                // Calcula para quanto tem que dividir para voltar as casas decimais
                var dec = valor.substring(valor.indexOf(",")+1).length; // Casas decimais
                var ndec =  Math.pow(10, dec); // Valor para calcular (10 elevado ao número de casas decimais)
            }

          // Remove pontos, vírgulas e espaços em branco
          valor = valor.replace(/\,\./, "").trim();
          
          // Transforma para numérico inteiro e depois divide para o quantidade de casas decimais
          valor = parseInt(valor) / ndec;
            
          // Calcula a formula
          var precoDeVendaRealizado = valor * (1 - valor + valor) / 100 ;
          // Transforma em string voltando o divisor decimal para vírgula
          var visivel = precoDeVendaRealizado.toString().replace('.',',');

$("#result").text('Calculo: '+visivel);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="precoVendaNoMercado" value="54,21"> <button id="go">GO</button>
<p id="result"></p>

I didn’t quite intend the purpose of the formula, but the way it is could be summed up for valor / 100.

1

You must create a function or make a comma-taking routine in the same way. Comma is considered text (string) and no calculations are made with text.

But the right thing is to replace the comma by the dot. And take the dots out of the thousands.

replace can help you.

var valor = '190.000,00';
var valorFormatado = valor.replace('.', '').replace(',', '.');

Hence yes you can do the calculation, since the point is not considered as text if it is not in quotes.

  • how do you get values like 1,000,000,000, using this replace('.', '). replace(',', '.')? Something else, how to comment or respond, with code formatting?

Browser other questions tagged

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