Get the value Before the Decimal Point in JavaScript


Borislav Hadzhiev

Last updated: Oct 25, 2021


Photo from Unsplash

Get the value Before the Decimal Point #

To get the value before the decimal point:

  1. Convert the number to a string and use the split() method to split it on the dot.
  2. The split method will return an array containing the values before and after the decimal.
  3. Access the array element at index 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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.