This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 5 months ago.
Let's suppose I have an integer value as
const num = 123456789
and I want to print the sum of these no. in react as 1+2+3+4+5+6+7+8+9 = 45
expect output = 45
approach I am following is as follows
const [total, setTotal] = useState(0);
const num = 123456789
for (const element of num ) {
setTotal(total + element)
}
console.log(total)
Output I am getting is : 01
Need your help here please!
You can continuously divide by 10 until the number becomes 0 and use % 10 to get the last digit.
let num = 123456789;
let sum = 0;
for (; num; num = Math.floor(num / 10))
sum += num % 10;
console.log(sum);
A one-liner
const num = 123456789
console.log(num.toString().split('').reduce((acc, elem) => elem*1+acc, 0))
Related
const reversedNum = num =>
parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
console.log(reversedNum(456))
Couldn't figure it out how to write code in order to sum 654 + 456
Thank You very much!
const reversedNum = num => num + +num.toString().split('').reverse().join('')
You can return sum of num and reversedNum inside a function.
const sumOfNumAndReversedNum= num => {
const reversedNum = parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
return num + reversedNum
}
let userNumber = 456
console.log(sumOfNumAndReversedNum(userNumber))
You can write a more performant way of reversing the number than turning it into a string, flipping it, and turning it back into an integer.
One option is to go through the number backwards by popping off the last integer (e.g., 123 % 10 === 3) and adding it to your newly reversed number. You'll also need to multiply your reversed number by 10 in each iteration to move you to the next degree.
For example, given the number 123:
123 % 10 = 3;
123 /= 10 = 12;
0 * 10 + 3 = 3;
1 % 10 = 2;
12 /= 10 = 1;
3 * 10 + 2 = 32
1 % 10 = 1;
1 /= 10 = 0;
32 * 10 + 1 = 321
This method will also automatically take care of negative numbers for you, leaving you something like:
function reverse(num) {
let reversed = 0;
while (num !== 0) {
const popped = num % 10;
num = parseInt(num / 10);
if (reversed > Number.MAX_VALUE / 10 || (reversed === Number.MAX_VALUE / 10 && popped > 7)) return 0;
if (reversed < Number.MIN_VALUE / 10 || (reversed === Number.MIN_VALUE / 10 && popped < -8)) return 0;
reversed = reversed * 10 + popped;
}
return reversed;
}
Now you can simply call:
console.log(123 + reverse(123))
const reversedNum = num =>
Number(num.toString().split('').reverse().join(''))
console.log(reversedNum(456))
Do it!
I'm trying to to increment the last decimal of a number from 1.234 to 1.235
var numb = 1.234;
numb.replace(/\d$/, numb + 1);
or let just say that the problem is like following
var oNumber = 1.34567
var oDecimalCount = 5
increaseNumber(oNumber, oDecimalCount){
oNumber += //increase the 5th(oDecimalCount) decimal place
}
You could do this :
count the numbers after the decimal point
use this number to remove the decimal point * 10^n
add 1
use the number to place the decimals back in place / 10^n
//I found this function here : https://www.tutorialspoint.com/decimal-count-of-a-number-in-javascript
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
let numb = 1.234;
let count = decimalCount(numb);
console.log(((numb * 10 ** count) + 1) / 10 ** count);
Im not sure I understand the question completely, but can't you just do it like this
let numb = 1.234;
numb += 0.001;
This question already has answers here:
Round number up to the nearest multiple of 3
(13 answers)
Closed 1 year ago.
I have a math problem like this:
When I enter a number, I find the nearest larger number that is divisible by a number x
Example: x = 50
Input = 20 => output = 50
Input = 67 => output = 100
Input = 200 => output = 200
Input = 289 => output = 300
Input = 999 => output = 1000
.......
I have a function below, but is there a way to make it faster?
console.log(roundNumber(199));
function roundNumber(n) {
let x = 50;
let flg = false;
while (flg === false) {
if (n > x) {
x += 50;
} else {
flg = true;
}
}
return x;
}
Yes, you can divide the input value by 50, take the "floor", add 1, and then multiply by 50.
function roundNumber(n) {
let x = 50;
return (Math.floor((n + x - 1) / x)) * 50;
}
Whether this will be much faster is kind-of irrelevant, unless for some reason you're performing this operation thousands and thousands of times over a short interval.
This question already has answers here:
Sum all the digits of a number Javascript
(8 answers)
Closed 6 years ago.
given var num = 123456 how can I find the sum of its digits (which is 21 in this case) without using arrays?
var num = 123456, sum = 0;
while ( num > 0 ) { sum += (num % 10)|0; num /= 10; }
document.write(sum);
Hope this helps.!
console.log(sumofdigits(123456));
function sumofdigits(number) {
var sum = 0;
while (number > 0) {
sum += number % 10;
number = Math.floor(number / 10);
}
return sum;
}
Added console.log() as suggested by #nnnnnn
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 ] : []