float <> string

Share your ZGE-development tips and techniques here!

Moderator: Moderators

Post Reply
User avatar
Kjell
Posts: 1715
Joined: Sat Feb 23, 2008 11:15 pm

float <> string

Post by Kjell » Tue Mar 29, 2011 3:05 pm

: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

StevenM
Posts: 149
Joined: Thu Jan 20, 2011 10:03 am

Post by StevenM » Sat May 28, 2011 4:20 pm

Useful function, thanks!

Post Reply