How does the 'parseFloat ()' function work?
I wanted someone to explain to me how this function works. For example:
What is the difference from:
var valor1 = 50;
var valor2 = 40;
var result = valor1 + valor2
For:
var valor1 = 50;
var valor2 = 40;
var result = parseFloat(valor1) + parseFloat(valor2);
1 answers
In the example you gave, parseFloat is not doing anything because you are passing integer values into it.
It serves to convert string into a floating point number value (houses after the comma in English, 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 are going to work 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
Since Javascript works with weak typing, it is also possible to convert a numeric value within 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 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 add 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 mathematical operation in 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).