Javascript - How do I get the last digit after the decimal number?

eg,

var myNum = 1.208452

      

I need to get the last digit myNum after the decimal, so this is (2)

+3


source to share


4 answers


You can try something like:

var temp = myNum.toString();
var lastNum = parseInt(temp[temp.length - 1]); // it 2

      

Edit



You might want to check if your number is an actual decimal, you can do:

var temp = myNum.toString();
if(/\d+(\.\d+)?/.test(temp)) { 
    var lastNum = parseInt(temp[temp.length - 1]);

    // do the rest
}

      

+5


source


This approach:

var regexp = /\..*(\d)$/;
var matches = "123.456".match(reg);
if (!matches) { alert ("no decimal point or following digits"); }
else alert(matches[1]);

      



How it works:

\.    : matches decimal point
.*    : matches anything following decimal point
(\d)  : matches digit, and captures it
$     : matches end of string

      

+2


source


As noted in the comments, I initially misunderstood your question and thought you needed the FIRST digit after the decimal point, which is what this one-line liner does:

result = Math.floor((myNum - Math.floor(myNum)) * 10);

      

If you want a purely mathematical solution that gives you the LAST digit after the decimal place, you can convert the number until the last digit is the first after the decimal point, and THEN use the above code like this (but it's not that long nice one-line):

temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);

      

How it works:

the above code multiplies temp by 10 until there is nothing after the decimal place, then divides by 10 to get a number with one digit after the decimal place, then uses my original code to give you the first digit after the decimal place! Phew!

+2


source


Just do:

function lastdigit(a)
{
    return a % 10;
}

      

-2


source







All Articles