How does parseFloat()' function work?

Asked

Viewed 11,808 times

9

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

What is the difference of:

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

To:

  var valor1 = 50;
  var valor2 = 40;
  var result = parseFloat(valor1) + parseFloat(valor2);

1 answer

17


In the example you gave, parseFloat is doing nothing because you are passing integer values into it.

It serves to convert string in a floating point number value (boxes after the comma in Portuguese, in the case of javascript the point).

For example:

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

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

parseInt('50.5'); // 50

Since Javascript works with weak typing, it is also possible to convert a numerical value within a string just by using a mathematical operator, for example:

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

However, if your string contains alphabetic 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.

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 last case where I try to add a mathematical 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).

  • You could edit your response by showing a functional example of it in a mathematical operation.

  • 1

    @Samirbraga added examples :)

  • Thank you very much, now it’s clear.

  • Very good explanation! Gabriel.

  • ball show. the best explanation about these errors that occur that I have found

Browser other questions tagged

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