Numbers extraction in JavaScript
The Number
function only works on
strings containing numbers. However,
when programming in JavaScript, there
are often situations where you need to
deal with strings that start with a number
and then letters.
An example of such a string can be a value
in pixels: '12px'
. Suppose we need
to get the number at the beginning, discarding
the string part. For such an operation, there
is a function parseInt
. Let's see how
it works with an example:
let num = parseInt('12px');
alert(num); // shows 12
Pixels, however, are sometimes fractional:
'12.5px'
. In this case, the function
parseInt
passes and prints only the
integer part:
let num = parseInt('12.5px');
alert(num); // still shows 12
In general, perhaps this behavior is exactly
what you need. But if not, use the parseFloat
function, which extracts the number together
with its fractional part:
let num = parseFloat('12.5px');
alert(num); // shows 12.5
Of course, the absence of a fractional
part does not prevent the parseFloat
function from working correctly:
let num = parseFloat('12px');
alert(num); // shows 12
Given a variable with the value
'5px'
and a variable with the value
'6px'
. Find the sum of pixels from
the values of these variables and display
it on the screen.
Given a variable with the value '5.5px'
and a variable with the value '6.25px'
.
Find the sum of pixels from the values of these
variables and display it on the screen.
Modify the previous task so that the letters
'px'
are added to the output.
That is, if our sum is equal to 11.75
,
then let '11.75px'
be displayed on the screen.