e.g.,
var myNum = 1.208452
I need to get the last digit of myNum after decimal so it is (2)
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
}
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
As pointed out in comments, I initially misunderstood your question and thought you wanted the FIRST digit after the decimal place, which is what this one-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 transform the number until the last digit is the first one after the decimal place and THEN use the above code, like this (but it's no longer a nice one-liner):
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 yield a number with only a single digit after the decimal place then uses my original code to give you the first digit after the decimal place! Phew!
Just do:
function lastdigit(a)
{
return a % 10;
}
Related
Can someone show me how to write a function that adds 0's after the decimal if less than four digits appear after the decimal until 4 decimal spots long and trim digits from far right of decimal in excess of 4. These are strings. Don't want any rounding. For display only, not calculations. So for example:
719.843797 should remove last two digits to be 719.8437
21.947 should add one 0 to be 21.9470
1.3456 no change
Using toFixed or any sort of multiplication may result in rounding problems. Treating number as a string allows to avoid them. The function below passes all your given usecases. But this is kinda hacky. Though I'm not sure if there is a better way to fit your requirements.
function truncate4(x) {
var parts = x.toString().split('.'); // this is not i18n proof :(
var integral = parts[0];
var decimal = parts[1] || ''; // might be integer
return integral + '.' + (decimal + '0000').substr(0, 4)
}
console.log(truncate4(719.843797));
console.log(truncate4(21.947));
console.log(truncate4(1.3456));
This function should match
function arrondir(num){
var str = num.toString();
var index = str.indexOf(".");
var decimal = str.substr(index+1);
var integer = str.substr(0, index);
if (decimal.length < 4)
for (var i = 0; i < 5 - decimal.length; i++)
decimal = decimal.concat("0");
else decimal = decimal.substr(0,4);
return integer.concat(".").concat(decimal);
}
console.log(arrondir(719.84)); // 719.8400
console.log(arrondir(719.84657963657)); // 719.8465
So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);
I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000
I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>
JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));
How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.
How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}
Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.
What's the best way to get the Nth digit of a number in javascript?
For example, for 31415926, the function will return 1 if N=2.
EDIT: And if possible, tu return directly a number, not a string.
EDIT 2: It is from left to right.
Try with that : (''+number)[nth] or (''+number)[nth-1] if one-based.
Personally, I would use:
function getNthDigit(number, n){
return parseInt((""+number).charAt(n));
}
But if you don't want it to be in String form ever you could use:
function getNthDigit(number, n){
var num = number,
digits = 0;
do{
num /= 10;
digits++;
}while(num>=1);
num = number / Math.pow(10, (digits - n));
num -= num % 1;
return (num % 10);
}
On second thought, just use the first option.
UPDATE: I didn't consider the fact that it was counting from the right. My bad!
Anyway, considering that the input is STILL a string, I'd use the same function, just with a little tweak.
Why don't you use the CharAt function? I think is the best option, considering the risk of multi-byte strings!!!
EDIT: I forgot the example:
var str = "1234567";
var n = str.charAt(str.length-2); // n is "6"