Borislav Hadzhiev
Mon Oct 25 2021·1 min read
Photo by Vikas Anand Dev
To get the value before the decimal point:
split()
method to split it on
the dot.split
method will return an array containing the values before and
after the decimal.0
and convert it back to a number.function getValueBeforeDecimal(num) { const beforeDecimalStr = num.toString().split('.')[0]; return Number(beforeDecimalStr); } console.log(getValueBeforeDecimal(123.456)); // 👉️ 123 console.log(getValueBeforeDecimal(1)); // 👉️ 1 console.log(getValueBeforeDecimal(-7.347)); // 👉️ -7 console.log(getValueBeforeDecimal(0.75)); // 👉️ 0
If you need to get the part after the decimal, check out my other article Get the Decimal Part of a Number.
We created a reusable function that returns the value before the decimal point.
We had to convert the number to a string, so we can call the String.split method on it.
The split
method takes a separator as a parameter and splits the string into
an array of substrings.
console.log('23.45'.split('.')); // 👉️ ['23', '45'] console.log('0.34'.split('.')); // 👉️ ['0', '34'] console.log('7.7'.split('.')); // 👉️ ['7', '7']
The last step is to convert the string back to a number and return the result.