This question already has answers here:
Split large string in n-size chunks in JavaScript
(23 answers)
Closed 5 months ago.
I am trying to solve a math problem where I take a number e.g. 45256598 % 2==0 and then split the number into separate two char digits like e.g. 45,25,65,98. Does anyone know how to split a number into individual two char digits?
I Have Already Achieved this C# code but this Method I am looking in JavaScript code :-
My C# code is:-
string str = "45256598";
int n = 2;
IEnumerable<string> numbers = Enumerable.Range(0, str.Length / n).Select(i => str.Substring(i * n, n));
You can do this by using match
like this:
const splittedNumbers = "45256598".match(/.{1,2}/g)
This will return array of:
['45','25','65','98']
If you would like to split in different length, just replace 2 with the length
const splittedNumbers = "45256598".match(/.{1,n}/g)
Hope this will help you!
<!DOCTYPE html>
<html>
<body>
<script>
const str = "45256598";
if((str * 1) % 2 === 0) {
const numArr = [];
for(let i = 0; i < str.length; i = i + 2) {
const twoDigit = str.charAt(i) + (str.charAt(i+1) ?? ''); // To handle odd digits number
numArr.push(twoDigit);
}
let result = numArr.join(',');
console.log(result);
}
</script>
</body>
</html>
Related
I have an integer and want to create an array from each of its numbers.
let interget = 345;
//I want create the array [3,4,5]
Is there any easy way to do this using Array.from() or would I need to convert the number to a string first?
easy way by converting to string
(inputNumber + "").split("").map(char => +char)
basically we split string and convert each character back to number
doing it manually
function getDigits(n) {
const ans = [];
while(n > 0){
let digit = n % 10;
ans.push(digit);
n -= digit;
n /= 10;
}
return ans.reverse();
}
Or you can do it like this:
var result = Array.from('345', Number)
console.log(result);
This question already has answers here:
HTML input type="number" still returning a string when accessed from javascript
(9 answers)
Closed 3 years ago.
This is a pretty basic SIP calculator that should not take more than 5 lines. But the variable amount is constantly being treated as a string. I have to keep using parseFloat() and declare three additional variables to store the final values before returning them for the code to work. Is there any workaround?
function sipCalculator(amount, r, n) {
r = r / 12;
amount = parseFloat(amount);
var temp = 0;
for (var i = 0; i < n; i++) {
temp += amount;
temp += (temp * (r / 100));
}
var x = amount * n;
var y = parseFloat(temp.toFixed(2));
var z = parseFloat((y - x).toFixed(2));
return [x, y, z];
};
The call to .toFixed(2) is converting the numbers to a string. If you instead want them to be numbers, while limiting them up to two decimal places, then parseFloat(num.toFixed(2)) is the recommended approach (which you are already doing).
Here's MDN's documentation on Number.prototype.toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
If you just don't like the verbosity of parseFloat, you can use + instead to convert the string to a number. Of course that's not the best idea as not everyone would know what it does.
var x = 1.44444;
console.log(+x.toFixed(2));
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 want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)
I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.
so this is my code for 2 digit numbers:
var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5
and this is my code for 3 digit numbers:
var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15
but I cant write a code to work with each number.How can I write a global code for each number?
In modern browsers you can do an array operation like
var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
return sum + +val
}, 0)
Demo: Fiddle
where you first create an array digits then use reduce to sum up the values in the array
var num = 4563;
var sum = 0;
while(num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);
Do number%10(modulus) and then number/10(divide) till the number is not 0
I hope the following example is useful to you:
var text="12345";
var total=0;
for (i=0;i<text.length;i++)
{
total+= parseInt(text[i]);
}
alert(total);
This solution converts the number to string, splits it into characters and process them in the callback function (prev is the result from the previous call, current is the current element):
var a = 456;
var sum = a.toString().split("").reduce(function(prev, current){
return parseInt(prev) + parseInt(current)
})
Here is how I would approach the problem. The trick I used was to split on the empty string to convert the string to an array and then use reduce on the array.
function digitSum(n) {
// changes the number to a string and splits it into an array
return n.toString().split('').reduce(function(result, b){
return result + parseInt(b);
}, 0);
}
As mentioned by several other posters (hat tip to my commenter), there are several other good answers to this question as well.
Here is my solution using ES6 arrow functions as call back.
- Convert the number into a string.
- Split the string into an array.
- Call the map method on that array.
- Callback function parse each digit to an array.
let number = 65535;
//USING MAP TO RETURN AN ARRAY TO DIGITS
let digits = number.toString()
.split("")
.map(num => parseInt(num));
//OUTPUT TO DOM
digits.forEach(
digit =>
document.querySelector("#out").innerHTML += digit + "<br>"
);
<p id="out"></p>
1) You can cast input number to string, using .toString() method and expand it into array with spread (...) operator
const splitNumber = n => [ ...n.toString() ]
2) Another short way - using recursion-based solution like:
const splitNumber = n => n ? [ ...splitNumber(n/10|0), n%10 ] : []
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
How can I take a JavaScript integer of arbitrary length, such as 1234567890, and format it as a string "1,234,567,890"?
You can use toLocaleString() for the format that you have asked.
var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();
The best way is probably with a regular expression. From How to print a number with commas as thousands separators in JavaScript:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
My solution:
var number = 1234567890;
var str = number + "";
var result = str.split('').map(function (a, i) {
if ((i - str.length) % 3 === 0 && i !== 0) {
return ',' + a;
} else {
return a;
}
}).join('');
See fiddle.