Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to get the last digit after decimal number?

Tags:

javascript

e.g.,

var myNum = 1.208452

I need to get the last digit of myNum after decimal so it is (2)

like image 511
mediaroot Avatar asked Oct 19 '25 11:10

mediaroot


2 Answers

You could try something like:

var temp = myNum.toString();
var lastNum = parseInt(temp[temp.length - 1]); // it's 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
}
like image 109
Dimitar Dimitrov Avatar answered Oct 21 '25 12:10

Dimitar Dimitrov


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 this works:

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