How does the 'parseFloat ()' function work?

8

I wanted someone to explain to me how this function works. For example:

What's the difference:

  var valor1 = 50;
  var valor2 = 40;
  var result = valor1 + valor2

To:

  var valor1 = 50;
  var valor2 = 40;
  var result = parseFloat(valor1) + parseFloat(valor2);
    
asked by anonymous 20.03.2014 / 22:12

1 answer

15

In the example you gave, parseFloat is not doing anything, as you are passing integer values into it.

It is used to convert string to a floating-point number value (houses after the comma in Portuguese, in the case of javascript the dot).

For example:

var valorStr = '50.5';
var parseValorStr = parseFloat(valorStr);
typeof valorStr // string
typeof parseValorStr // number

If you are working with integer values you can use parseInt , but if the string you are converting has a decimal value, it will remove this value.

parseInt('50.5'); // 50

As Javascript works with poor typing, it is also possible to convert a numeric value inside a string only using a mathematical operator, for example:

var valor = '50.5';
typeof +valor // Number (neste caso 50.5)

But if your string contains alpha characters, it is important to use parseFloat or parseInt to maintain the integrity of the application, because if you use + in a string that contains non-numeric characters, it will concatenate the values and not sum them up.

Example:

+'50.5' + 50; // 100.5
'50.5' + 50; // 50.550
parseFloat('50.5') + 50; // 100.5
parseInt('50.5') + 50; // 100
parseFloat('50.5a') + 50; // 100.5
'50.5a' + 50; // 50.5a50
+'50.5a' + 50; // NaN

In the latter case where I try to add a math operation to the string '50.5a' javascript tries to convert to a numeric value but when it finds the letter a it stops the operation and returns a value that identifies as Not a Number ( NaN , Not a Number).

    
20.03.2014 / 22:22