how could i split a number 0-999 into its ones tens and hundreds digit?
the code i have now is not working correctly
speedCount = 888;
hundreds = speedCount / 100;
tens = speedCount / 10;
ones = speedCount % 10;
it is making 888 into
ones: 8
tens: 88
hundreds: 8
it should be
ones: 8
tens: 8
hundreds: 8
What is a simple way i can turn a three number into its digits?
Take a look at Arduino/reference, math, operators..! It's a great toolbox!Don't miss the modulo operator %!
Integer division by 10 and 100 are among the possibilities, along with subtraction.
Hint: so is the "%" integer remainder operator.
you can also subtract the result of the preceding calculation from spedcount for tens and units to correct this problem..
6v6gt
6
tens = (speedCount / 10) % 10 ;
Assume that you have the number 789 and you want to extract these factors 7 (0x07), 8 (0x08), and 9 (0x09).
int myNum = 789; //D2D1D0
byte D0 = myNum%10; //D0 = 09
Serial.println(D0, DEC); //shows: 9
myNum = myNum/10; //myNum = 78
byte D1 = myNum%10; //D1 = 08
Serial.println(D1, DEC); //shows: 8
myNum = myNum/10; //myNum = 7
byte D2 = myNum%10; //D2 = 07
Serial.println(D2, DEC); //shows: 7
Or
byte myFactor[3]; //array to hold positional factors of 789
int myNum = 789;
for(int i = 0; i < 3 ; i++)
{
myFactor[i] = myNum%10; //myFactor[0] = 0x09 ==> 9
myNum = myNum/10;
}
This is for 4 digits, the logic is the same for three digits.
uint16_t value = 9876;
uint8_t thousands;
uint8_t hundreds;
uint8_t tens;
uint8_t ones;
thousands = value/1000;
hundreds = (value/100) % 10;
tens = (value/ 10) % 10;
ones = value % 10;
for example, for value equal to: 0, 1, 9, 56, 70, 289, 2386, 9999: