Float to Char question

I have a problem with converting some float result to char.
For example converting 1.05 to char, become 1.5.

The code for the converting prosess:

char* FtoChar2(float fVal, char* cF) {

  // Force number of decimal places to full 2
  int iDigs = 2;

  // Separator = 10 ˆ Number of decimal places
  long dSep = pow(10, iDigs);

  // Display value = floal value * separator
  signed long slVal = fVal * dSep;

  sprintf(cF, "%d.%d", int(slVal / dSep), int(slVal % int(dSep)));
}
FtoChar2(battV, cbattV);     // this is the exampe, battV is 13.08, but the cbattV result become 13.8

Can anyone help me here? :slight_smile:

%d will not print leading zero's, use %0d instead (that is the number 0, not the letter O).

There is already a function for converting a float to char array, dtostrf()

Consider using the dtostrf() function to convert the float to a char array

  float aFloat = 1.05;
  dtostrf(aFloat, 2, 2, buffer);
  Serial.println( buffer);

Change the parameters to suit what you need

Thank you both very much

I see I made a mistake, should be %02d to specify the field width.

@OP

1. Your given float number is:

float y = 13.08;

2. You want ASCII codes for '1', '3', '.', '0', and '8'. That means there will be 5 elements in the output string. The ASCII codes for the elements are: 0x31, 0x33, 0x2E, 0x30, and 0x38.

3. The following C-function could be used to get the ASCII codes of the given float number.

dtostrf(arg1, arg2, arg3, arg4);

Where:
arg1 = float value = 13.08
arg2 = Number of ASCII codes in the output string = 5 (called field width)
arg3 = Number of digits after decimal point = 2 (called precision)
arg4 = Null terminated array to hold output string. (char myArray[10] = "";)

==> dtostrf(y, 5, 2, myBuffer);

4. The sketch

void setup() 
{
  Serial.begin(9600);
  char myBuffer[10] = "";
  float y = 13.08;
  dtostrf(y, 5, 2, myBuffer);  
  for(int i=0; i<5; i++)
  {
    Serial.print(myBuffer[i], HEX); //shows: 31 33 2E 30 38
    Serial.print(' ');
  }
  Serial.println();
  Serial.println( myBuffer);  //show: 13.08

}

void loop() 
{
 
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.