Error adding sums with decimals in javascript

2

I'm trying to add N values with decimals with javascript, the problem is that it manages to add: example 53.113,20 + 12,50 = Unexpected number

I have a function that converts my totals in currency format:

Number.prototype.formatMoney = function(c, d, t){
            var n = this, 
                c = isNaN(c = Math.abs(c)) ? 2 : c, 
                d = d == undefined ? "." : d, 
                t = t == undefined ? "," : t, 
                s = n < 0 ? "-" : "", 
                i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), 
                j = (j = i.length) > 3 ? j % 3 : 0;
            return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
         };

Example:

var x = 53113,20;
x.formatoMoneda(2, '.', ',');
var y = 12,50;
y.formatoMoneda(2, '.', ',');

The result would be this:

x = 53.113,20;
y = 12,50

By adding x+y = ERROR.

    
asked by Jhosselin Giménez 08.04.2017 в 02:19
source

3 answers

4

In JavaScript there is no concept of number formats, which is what you are doing when you declare these numbers. In JavaScript, there is only one format and it is:

<parte entera>.<parte decimal>

Therefore, the numbers you declare must be changed to:

var x = 53113.20;
var y = 12.50;

The literal comma, mainly separates expressions, for example:

var x = 53113.20,
    y = 12.50;

When finding a comma, the engine waits for a statement ; in this specific case, expects an assignment from a value to a variable when it is inside a statement statement.

  

What happens is that the totals are products and I'm passing that to a function that converts me to currency format.

That does not apply when working with programming . Neither the programming languages nor the databases are interested in having a currency format (of the several internationally available). You can insert these same numbers in a database without any problem.

A different case for which applies what you explain, is when you want to generate certain files where you keep a currency format , as is the case of a spreadsheet. In that case, you just have to make a small function to convert a Number to a text representation according to a specific format.

The librarian Numeral.js allows you to format a JavaScript number to a specific format. In your case, the format must be 0,0.00 :

const x = 53113.20;
const y = 12.50;

console.info(numeral(x + y).format('0,0.00'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
    
answered by 08.04.2017 / 02:29
source
0

the comma is not needed, to be able to differentiate if it is integer or decimal, divide them by the . point

var x = 53113.20;
var y = 12.50;
var total = x + y;

console.log(total);
    
answered by 08.04.2017 в 02:28
0

Short answer

  • In JavaScript, the decimal point separator is the point
  • Functions to format numbers return strings.
  • Explanation

    Then I explain what is indicated above, in parts, first the assignment of numbers to variables and then the use of native functions.

    First part: Assigning numbers to variables

    In the Mozilla Developer Network (MDN) guide on how to work with numbers and dates it is not explicitly stated that the decimal point separator is the point, however, when viewing the examples this can be identified.

    Then when assigning a number to a variable in JavaScript instead of

    var x = 53113,20;
    

    The correct thing is

    var x = 53113.20;
    

    and instead of

    var y = 12,50;
    

    the correct thing is

    var y = 12.50;
    

    Second part: Format of numbers

    What we usually call format in the MDN JavaScript documentation calls it "representation of the number according to the language". For this, JavaScript includes two functions natively

    The second is recommended when large amounts of numbers are going to be converted, because it performs better, according to MDN.

    Integrating the above the code would be as follows

    // Asignación de variables a número
    var x = 53113.20;
    var y = 12.50;
    
    // suma
    var suma = x + y;
    
    // Formato
    var options = {minimumFractionDigits:2} // Con esto aseguramos que se muestren 2 decimales como mínimo
    console.info('x: ' + x.toLocaleString('es-ES',options));
    console.info('y: ' + y.toLocaleString('es-ES',options));
    console.info('suma: ' +suma.toLocaleString('es-ES',options));

    It should be noted that the previous functions have limitations in terms of their compatibility with browsers, but they work in the main browsers in their recent versions, as I understand it. How in the question is not mentioned objective browsers is considered this out of the scope of the discussion.

        
    answered by 11.03.2018 в 21:56