Go Down

### Topic: Easier way to convert float to char array (Read 3160 times)previous topic - next topic

#### tavovalencia

##### Feb 13, 2013, 11:35 pm
Hi guys, this time I actually worked my way around the problem, but I was wondering if you could share some ideas about how to improve the following code. I'm reading an array of chars from an eeprom, I later transform this array via atof() and do some mathematical operations and the last thing to do is write back to the memory the new floating number in the form of an array of chars (lucky me that I only have 4 significant figures i.e.: 71.53).

Just wondering if "I discovered the wheel" (Spanish expression meaning that this was done before) and that It was much easier that I thought. If so, could you point me in that direction. If not, then this is my workaround.

PS: I'm trying to reduce the basic sketch size as much as possible.

Code: [Select]
`//Number 71.53 to convert to FArray{ 7, 1, ., 5, 3}float F = 71.53;char FArray[6];//Temporal Variables that hold figures (i.e.: F10 = tens, F1 = ones)int Fint, F10, F1, F01, F001;//Temporal variable that holds Moduloint Mod1, Mod01;void setup(){ Serial.begin(9600);}void loop(){ floatToArray();        delay(20000);}void floatToArray(){ Serial.println(F);  //Float to convert        F = F * 100;        Fint = (int)F;        Mod1 = Fint % 1000;        F10 = (Fint - Mod1)/1000; Serial.println(F10); // Tens        F1 = (Fint - (F10*1000));        Mod01 = F1 % 100;        F1 = (F1 - Mod01)/100;        Serial.println(F1); // Ones        Serial.println('.'); // just printing the dot        F01 = (Mod01 - (Mod01%10))/10;        Serial.println(F01); // 1st decimal figure        F001 = (Mod01 - (F01*10));        Serial.println(F001); //2nd decimal figure FArray[0] = F10+48; //converting number to ascii FArray[1] = F1+48; //converting number to ascii FArray[2] = '.'; FArray[3] = F01+48; //converting number to ascii FArray[4] = F001+48; //converting number to ascii Serial.println(FArray);}`

#### krupski

#1
##### Feb 13, 2013, 11:38 pm

Hi guys, this time I actually worked my way around the problem,

What's wrong with "printf("%f", value)"?
Gentlemen may prefer Blondes, but Real Men prefer Redheads!

#### tavovalencia

#2
##### Feb 13, 2013, 11:42 pm
There is nothing wrong with it, I'm printing the line to confirm that my code is right.
The main goal is to save the float as an array of chars i.e.: float number 71.53 to Array[]={'7','1','.','5','3'}

#### PaulS

#3
##### Feb 14, 2013, 12:02 am
I'm curious why you want to convert 5 bytes of EEPROM data to a 4 byte float value and back. Far simpler to just save the 4 bytes into, and read the 4 bytes from, the EEPROM.