Adding array in currency javascript

5

I need some help to convert and add fields formatted as currency coming in this format "1,568,78"

I have a code that sums an array of plots and checks if it is equal to the total phallus of the invoice I got here after several queries in user responses, and works perfectly with integer numbers, but when I type the number formatted in reais it does not sum:

var quant = document.getElementsByName("valor[]");
function somarValores(){
var valor_fatura = parseInt(document.getElementById('valor_fatura').value);
var soma = 0;
var soma = [].reduce.call(quant, function (somatorio, el) {
    return somatorio + parseInt(el.value, 10) || 0;
}, 0);
if(soma != valor_fatura){
 alert('Valor não confere. Fatura='+valor_fatura+' - Parcelas='+soma+'');
 return false;
}

}

I then assume that I have to convert the "quant" and "value_value" variables to 1568.78 before calculating because it is rounded to integers and disregards the cents causing my validation error

    
asked by anonymous 30.11.2015 / 03:27

3 answers

4

Well, the tips helped me a lot. I was able to solve by removing the punctuation of the string and using the parseFloat inside the own code so as not to have an immense code.

var quant = document.getElementsByName("valor[]");
function somarValores(){
var valor_fatura = parseFloat(document.getElementById('valor_fatura').value.replace('.','').replace(',','.'));
var soma = 0;
var soma = [].reduce.call(quant, function (somatorio, el) {
    return somatorio + parseFloat(el.value.replace('.','').replace(',','.'), 10) || 0;
}, 0);
if(soma != valor_fatura){
var diferenca = soma - valor_fatura;
$("#lcto_mostraerro").append("Valor não confere. Há uma diferença de "+parseFloat(diferenca)+"");
return false;
}    
}

First include the parseFloat at the beginning of the string and retreat the punctuation with replace ".replace ('.', '') replace (',', '.')".

To give an incremental use .append to show the error inside a div instead of alert

    
30.11.2015 / 11:03
4
  • Remove the dot character (.)

  • Replace the comma (,) with period (.)

  • str = '1.568,78901';
    str = str.replace(/[.]/g, '');
    str = str.replace(/[,]/g, '.');
    console.log(str);
    document.getElementById('foo').innerHTML = str;
    
    
    /**
    Uma situação muito perigosa, inclusive citada num dos comentários, consiste em remover o ponto e a vírgula e dividir por 100. 
    Isso não é seguro pois se trabalharmos com casas decimais maior ou menor que 2 casas, retornará um número errado.
    */
    str = '1.568,78901';
    str = str.replace(/[.,]/g, '');
    str = parseInt(str) / 100;
    console.log(str);
    document.getElementById('foo2').innerHTML = 'cuidado... o resultado é errado: '+str;
    <div id="foo"></div>
    <br />
    <div id="foo2"></div>

    To perform mathematical operations, always use parseInt () or parsetFloat () to convert the strings to a numeric format for calculations.

    Function names are suggestive "Int" for integers and "Float" is for floating numbers (with decimals).

    A more complete example, converting the numbers and performing a mathematical operation:

    function number_format(number, decimals, dec_point, thousands_sep) {
      //  discuss at: http://phpjs.org/functions/number_format/
      number = (number + '')
        .replace(/[^0-9+\-Ee.]/g, '');
      var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function(n, prec) {
          var k = Math.pow(10, prec);
          return '' + (Math.round(n * k) / k)
            .toFixed(prec);
        };
      // Fix for IE parseFloat(0.55).toFixed(0) = 0;
      s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
        .split('.');
      if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
      }
      if ((s[1] || '')
        .length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1)
          .join('0');
      }
      return s.join(dec);
    }
    
    
    function floatFilter(str)
    {
        str = str.replace(/[.]/g, '');
        str = str.replace(/[,]/g, '.');
        return parseFloat(str);
    }
    
    var n1 = '1.568,78901';
    var n2 = '5.311';
    var sum = floatFilter(n1) + floatFilter(n2);
    document.getElementById('foo3').innerHTML = n1+' + '+n2+' = '+sum+' ou ('+number_format(sum, 5, ',', '.')+')';
    <div id="foo3"></div>

    obs: The number_format() function is PHPJS.org project: link

    It is a project that translates PHP funtions to JavaScript.

        
    30.11.2015 / 07:48
    0

    Use JavaScript parseFloat (). If your string comes as "1,568.78" (example). You should do this:

    parseFloat("1.568,78") //1568.78
        
    30.11.2015 / 04:01