Borislav Hadzhiev
Mon Oct 25 2021·2 min read
Photo by Tyler Lastovich
To get the decimal part of a number:
0
.split()
method to
split it on the dot.1
to a number and return the result.const num = 12.345; function getDecimalPart(num) { if (Number.isInteger(num)) { return 0; } const decimalStr = num.toString().split('.')[1]; return Number(decimalStr); } console.log(getDecimalPart(12.345)); // 👉️ 345 console.log(getDecimalPart(-1.23)); // 👉️ 23 console.log(getDecimalPart(1)); // 👉️ 0
We created a reusable function that returns the decimal part of a number.
We used the Number.isInteger method to determine if the passed in number is an integer.
If the number is an integer, we return 0
straight away as it has no decimal
part.
Here are some examples of using the Number.isInteger
method.
console.log(Number.isInteger(5)); // 👉️ true console.log(Number.isInteger(-5)); // 👉️ true console.log(Number.isInteger(5.0)); // 👉️ true console.log(Number.isInteger(5.5)); // 👉️ false console.log(Number.isInteger('5')); // 👉️ false
5.00
are considered integers because 5.00
is the same as 5
and JavaScript automatically drops any insignificant trailing zeros from numbers.console.log(5.00 === 5); // 👉️ true
After we find out that the number isn't an integer, we convert it to a string and call the String.split method on it to split it on the dot.
The split
method takes a separator as a parameter and splits the string into
an array of substrings.
console.log('1.37'.split('.')); // 👉️ ['1', '37'] console.log('-3.58'.split('.')); // 👉️ ['-3', '58']
The decimal part of the number is stored in the array at index 1
. However, we
have to convert it back to a number before returning from the function.
1
and the last - an index of array.length -1
.An alternative approach is to use the modulo operator.
To get the decimal part of a number use the modulo (%) operator to get the
remainder from dividing the number by 1
, e.g. 3.17 % 1
. The modulo operator
returns the remainder of dividing one number by another.
function getDecimalPart(num) { return num % 1; } console.log(getDecimalPart(3.137)); // 👉️ 0.137 console.log(getDecimalPart(1.37)); // 👉️ 0.37000000000001 console.log(getDecimalPart(5)); // 👉️ 0
We used the modulo (%) operator to get the remainder of dividing the number by 1.
This gives us the number after the decimal, however floating point numbers don't represent all decimals precisely in binary, which sometimes leads to inconsistent results.
console.log(0.1 + 0.2 === 0.3); // 👉️ false
The sum of 0.1
and 0.2
is actually equal to 0.30000000000000004
instead of
0.3
. This is because the binary floating-point format cannot accurately
represent numbers like 0.1
or 0.2
.
The code gets rounded to the nearest number, resulting in a rounding error.