Page 1 of 1

float <> string

Posted: Tue Mar 29, 2011 3:05 pm
by Kjell
:arrow:

Conversion between floats & strings. No error checking on stringToFloat ( neither can you use the E keyword ), and floatToString is quick & dirty ( so the string might be off a fraction ).

Code: Select all

string floatToStr(float F, int D) // D = Number of decimals
{
  string S = F < 0 ? "-" : "";
  F = abs(F);
  int N = floor(F);
  S += intToStr(N)+".";

  F -= N;

  for(int B=0; B<D; B++)
  {
    F *= 10;
    N = floor(F);
    S += intToStr(N);
    F -= N;
  }

  return S;
}

//

float strToFloat(string S)
{
  int L, C, A, N, D;

  N = D = 0;
  L = length(S);

  float F = 0;

  for(C=0; C<L; C++)
  {
    A = ord(subStr(S,C,1));

    switch(A)
    {
      case 45: N = 1; break;
      case 46: D = 1; break;

      default:
        if(D)
        {
          F += (A-48)/pow(10,D);
          D++;
        }
        else
        {
          F *= 10;
          F += A-48;
        }
    }
  }

  if(N)F = 0-F;

  return F;
}
K

Posted: Sat May 28, 2011 4:20 pm
by StevenM
Useful function, thanks!