[JavaScript] How to Get the Number of Decimal Places

Tadashi Shigeoka ·  Thu, February 9, 2017

I’ll introduce how to get the number of decimal places in JavaScript.

JavaScript

getDecimalPlace Method to Get the Number of Decimal Places

/**
 * Get the number of decimal places
 * @param {Number} number
 * @return {Number} decimalPlace
 **/
var getDecimalPlace = function(number) {
  if (typeof number !== 'number') {
    return null;
  }

  var decimalPlace = 0;
  var numbers = number.toString().split('.');
  if (numbers[1]) {
    decimalPlace = numbers[1].length;
  }

  return decimalPlace;
};

Usage

When you specify a number as the first argument, the return value is the number of decimal places.

var number = 1234.56789;

getDecimalPlace(number); // 5
getDecimalPlace('not number'); // null

That’s all from the Gemba.