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.
– Samir Braga
@Samirbraga added examples :)
– Gabriel Gartz
Thank you very much, now it’s clear.
– Samir Braga
Very good explanation! Gabriel.
– user13460
ball show. the best explanation about these errors that occur that I have found
– user15428