user75521
user75521

Reputation: 59

Get the last digit of a decimal value in JavaScript

Is there any function in JavaScript that will return the unit size of the least significant digit of a decimal number?

For example:

And for an integer value, just return 1.

For example:

Upvotes: 2

Views: 209

Answers (1)

Michael Laszlo
Michael Laszlo

Reputation: 12239

Find the position of the period and compare it to the length of the string:

function smallestDecimalUnit(s) {
  var pos = s.indexOf('.');
  if (pos == -1) {
    return 1;
  }
  return Math.pow(10, pos - s.length + 1);
}

function test(s) {
  document.write(s + ' &rarr; ' + smallestDecimalUnit(s) + '<br><br>');
}

test('1.5');
test('0.15');
test('0.10');
test('15');
test('150');
body {
  font-family: sans-serif;
}

Upvotes: 4

Related Questions