In everyday life, we are covered with data and stats from attending college from 9
to travelling to 10 km
and its fare 100
.
These are some of the mathematics, we all use in our daily life.
Welcome to this blog & This blog is all about Numbers in JavaScript.
So, tighten your seat belt and let's start with this:
Numbers
We have following two types of Numbers in JS :-
Regular Number
BigInt numbers (a regular integer number can’t safely exceed
(2<sup>53</sup>-1)
or be less than-(2<sup>53</sup>-1)
)
How to show Numbers data in code🧑🏽💻
Let's supoose we are writing population of India i.e. 140 Billion in a variable pop_n
,
we can write it as
let pop_n = 13200000000;
obviously, we are not suppose to make mistake in writing no. of 0's,
so we will write it into an underscore _
as the separator
let pop_n = 13_200_000_000;
The underscore serves as the "syntactic sugar" in this case, making the number easier to read.
The JavaScript engine just ignores between digits, so it's the same one billion as before.
Instead, of writing zeroes in a sep too, we can just write as 132bn
for 132 billions.
Also, we have e also,
int pop_n = 132e8;
e is simply number of zeroes,
we can write decimal in e as:
1/10000 === 1.e-4;
Some other units of Numbers (Hex, binary and octal numbers)
Hexadecimal numbers are commonly used in JavaScript to represent colours, encode letters, and for a variety of other purposes.
So, naturally, there is a shorter method to write them: 0x
followed by the number.
alert( 0xff ); // 255
toString
The method num.toString(base)
returns a string representation of num
in the numeral system with the given base
.
let num = 255;
alert( num.toString(16) ); // ff
alert( num.toString(2) );
Round-Off
Rounding off is the basic operation while working with decimals.
Also, there are in-built functions for doing so,
Math.floor : It is rounding operation where
7.1
becomes7
, and-2.1
becomes-3
.Math.ceil : It is rounding operation where
7.1
becomes8
, and-2.1
becomes-2
.Math.round : It rounds to the nearest integer:
4.4
becomes4
,4.6
becomes5
.Math.trunc : Removes anything after the decimal point without rounding:
3.1
becomes3
These routines cover every feasible method for dealing with a number's decimal portion. What if we want to round the integer to the nth digit after the decimal?
For example, we have 4.5678
and want to round it to 2 digits, getting only 4.56
.
We can do it using 2 methods:
Multiply-and-divide
For example, to round the number to the 2nd digit after the decimal, we can multiply the number by
100
, call the rounding function and then divide it back.let num = 4.5678; alert( Math.round(num * 100) / 100 );
The method toFixed(n) rounds the number to
n
digits after the point and returns a string representation of the result.let num = 45.67; alert( num.toFixed(1) ); // "45.6"
This rounds up or down to the nearest value, similar to
Math.round
:let num = 12.36; alert( num.toFixed(1) ); // "12.4"
Please note that the result of
toFixed
is a string. If the decimal part is shorter than required, zeroes are appended to the end.let num = 12.34; alert( num.toFixed(5) ); // "12.34000", added zeroes to make exactly 5 digits
We can convert it to a number using the unary plus or a
Number()
call, e.g write+num.toFixed(5)
.
isFinite and isNaN
Infinity
(and-Infinity
) is a special numeric value that is greater (less) than anything.NaN
represents an error.
parseInt and parseFloat
Numeric conversions using plus (+) or Number() are rigorous. If a value is not an exact number, it fails:
alert( +"100px" ); // NaN
The only exceptions are spaces at the beginning and end of the string, which are disregarded.
However, in real life, we frequently use unit values, such as "100px
" or "12pt
" in CSS.
Also, in many countries, the currency sign appears after the quantity, so we get "19€" and want to extract a numerical value from it.
This is what parseInt and parseFloat are for.
They try to "read" a number from a string until they fail. In the event of an error, the collected number is returned. The method parseInt returns an integer, whereas parseFloat produces a floating-point number:
alert( parseInt('100px') ); // 100
alert( parseFloat('12.5em') ); // 12.5
alert( parseInt('12.3') ); // 12, only the integer part is returned
alert( parseFloat('12.3.4') ); // 12.3, the second point stops the reading
With the help of above example we can understand the concept of parseint, parsefloat.
The second argument ofparseInt(str, radix)
The parseInt()
function has an optional second parameter. It specifies the base of the numeral system, so parseInt
can also parse strings of hex numbers, binary numbers and so on:
alert( parseInt('0xff', 16) ); // 255
alert( parseInt('ff', 16) ); // 255, without 0x also works
alert( parseInt('2n9c', 36) ); // 123456
Other math functions
JavaScript has a built-in Math object which contains a small library of mathematical functions and constants.
A few examples:
Math.random
Returns a random number from 0 to 1 (not including 1).
Math.max(a, b, c...)
andMath.min(a, b, c...)
Summary
To write numbers with many zeroes:
Append
"e"
with the zeroes count to the number. Like:123e6
is the same as123
with 6 zeroes123000000
.A negative number after
"e"
causes the number to be divided by 1 with given zeroes. E.g.123e-6
means0.000123
(123
millionths).
For different numeral systems:
Can write numbers directly in hex (
0x
), octal (0o
) and binary (0b
) systems.parseInt(str, base)
parses the stringstr
into an integer in numeral system with givenbase
,2 ≤ base ≤ 36
.num.toString(base)
converts a number to a string in the numeral system with the givenbase
.
I hope you loved my blog! 💖
I love writing blogs and spreading amazing things with you people!
Connect me on Twitter, LinkedIn and GitHub!