Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

how do I cut up a number like 281 in javascript

Hi,

Can someone advise how I would cut up a number like 5000 or 281 in javascript and store into new variables.

thanks
0
jecommera
Asked:
jecommera
4 Solutions
 
Gurvinder Pal SinghCommented:
what do you mean by cut up?
0
 
jecommeraAuthor Commented:
So I will have

from 281, I get

a=2, b=8, c=1
0
 
Gurvinder Pal SinghCommented:
var val = 281;
var digits = new Array()
while (val > 0)
{
  digits[ digits.length ] = val%10;
  val = val /10;  
}

//now you can take the individual values out of digits array
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
jecommeraAuthor Commented:
Can you please explain the code.
thanks for your help
0
 
Gurvinder Pal SinghCommented:
i am simply removing the last digit the from variable in every iteration of the while loop and storing that last digit in the digits array

Kindly tell me if it works or not
0
 
jecommeraAuthor Commented:
Yes it works - I just trying to understand your code here.

Why did you use 10 here?

digits[ digits.length ] = val%10;
  val = val /10;
0
 
GreggCommented:
0
 
nap0leonCommented:
As an array:
var startingNumber = 281
var numArray = startingNumber.split('')

Open in new window


You can then put it into named variables if you want to... but this limits the ability to pass in different lengths of values (unless you want to make it super complicated).
0
 
ProculopsisCommented:
Strictly speaking this is what you want but consider using an array rather than individual variables:

var sample = 281;

var digit = sample.toString().match(/\d/g);

var index = -1;

while (++index != digit.length) {
    eval(String.fromCharCode(97 + index) + "=" + digit[index]);
}

alert("a = " + a + "\nb = " + b + "\nc = " + c);

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now