Get the value Before the Decimal Point in JavaScript


Borislav Hadzhiev

Mon Oct 25 20211 min read

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee