Pages: [1]   Go Down
 Author Topic: How do i go from: eg Number "125" ----split----> Numbers "1", "2", "5" ??? SLVD  (Read 250 times) 0 Members and 1 Guest are viewing this topic.
Offline
Jr. Member
Karma: 0
Posts: 80
 « on: November 17, 2012, 06:21:29 pm » Bigger Smaller Reset

I would like to know if there is any way (preferably simple) to split any number into its digits. For example split the number 125 (stored in variable A) into numbers 1,2 and 5 (which will then be stored in variables x,y,z respectively).

Thank you in advance and have a nice day
 « Last Edit: November 18, 2012, 03:31:50 am by Voidugu » Logged

France
Offline
God Member
Karma: 19
Posts: 623
Scientia potentia est.
 « Reply #1 on: November 17, 2012, 06:55:23 pm » Bigger Smaller Reset

Hello, the easiest way (I think), is doing something like this:
Code:
uint8_t x, y, z;
int number = 125;

z = number % 10;
y = (number /= 10) % 10;
x = number / 10;

Serial.println(x);
Serial.println(y);
Serial.println(z);
 « Last Edit: November 18, 2012, 12:21:06 am by guix » Logged

Central MN, USA
Offline
Karma: 35
Posts: 5938
Phi_prompt, phi_interfaces, phi-2 shields, phi-panels
 « Reply #2 on: November 17, 2012, 06:56:31 pm » Bigger Smaller Reset

There are several ways. I will go through two ways. Pick the one you understand better:
Use math to extract digits:
There is an operation "%" that does this:
125%10=5

http://arduino.cc/en/Reference/Modulo

Then you do 125/10, which gives you 12, remember integer math only gives you 12, not 12.5
With 12,
12%10=2

Then 12/10 gives 1,
1%10=1

If you collect all three % results, you get the three digits.

Next method, use text output. It may seem easy to you depending on how comfortable you are with math.

Assume int  value=125;
char result[10];
sprintf(result,"%04d",value);
Now result has "0125".
You can do
single=result[3]-'0';
tens=result[2]-'0';
hundreds=result[1]-'0';
thousands=result[0]-'0';

The above assumes up to 9999 positive numbers. Essentially the same math is used inside sprintf.
 Logged

France
Offline
God Member
Karma: 19
Posts: 623
Scientia potentia est.
 « Reply #3 on: November 18, 2012, 12:23:15 am » Bigger Smaller Reset

Here is a code based on liudr's second method:

Will work for any (positive) numbers...

Edit: Here a version which can handle negative numbers:

Hope this help..
 « Last Edit: November 18, 2012, 01:05:20 am by guix » Logged

Central MN, USA
Offline
Karma: 35
Posts: 5938
Phi_prompt, phi_interfaces, phi-2 shields, phi-panels
 « Reply #4 on: November 18, 2012, 12:33:50 am » Bigger Smaller Reset

Also, if you want to know sprintf, here is a tutorial:

http://liudr.wordpress.com/2012/01/16/sprintf/
 Logged

Offline
Jr. Member
Karma: 0
Posts: 80
 « Reply #5 on: November 18, 2012, 03:31:00 am » Bigger Smaller Reset

Thank you all very much people Your help is invaluable. Again thanx
 Logged

 Pages: [1]   Go Up