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).