I have, for example, a variable int number = 300; and i need modify "number" by "number", i wonder if i need separate in 3 variables for hundred, ten, unity or if there a method for divide that enable to me change a unique variable "number' by "number", "house" by "house", a hundred, a ten and unity (3 - 2 - 1).
Example: The user need only change number "2" of 3'2'1, and he want that "2" to being "5", as "321" must become to "351" . In other words, the number 3 and 0 not will modified, only number 2 from 321, turning 3-5-1.
Using Robins example you can do it in 4 lines including dtostrf() to convert the passed number to a char array,
unfortunately for me i overthought the process in the past and had to divide and multiply the number x times,
I see no need to post it, as quite frankly in comparison to Robins it is blotted but just for giggles here it is.
void setup()
{
Serial.begin(115200);
changeDigit(6789, 5, 1);
}
void loop()
{
}
long changeDigit(const long& a_num, const byte& a_newDigit, const byte& a_position) {
const byte numberOfDigits = countDigits(a_num);
Serial.print("numberOfDigits = "); Serial.println(numberOfDigits);
byte digits[numberOfDigits] {0};
unsigned long division = 1;
for (byte i = 0; i < numberOfDigits; i++) {
digits[i] = int(a_num / division) % 10;
division *= 10;
}
// Set new digit at a_position
if (a_newDigit <= 9 && a_position < numberOfDigits) {
digits[a_position] = a_newDigit;
}
// Add all the digits back into one number
division = 1;
long finalNumber = 0;
for (byte i = 0; i < numberOfDigits; i++) {
finalNumber += int(digits[i] * division);
division *= 10;
}
Serial.print(F("Final number = ")); Serial.println(finalNumber);
return finalNumber;
}
byte countDigits(long num) {
byte count = 0;
while (num > 0) {
num /= 10;
count++;
}
return count;
}