Difference between revisions of "String2Float"

From Second Life Wiki
Jump to navigation Jump to search
(... why does this exist? It is faster and eaiser to just use (float)"float value")
Line 10: Line 10:
'''Example:'''
'''Example:'''
<lsl>
<lsl>
float My_new_float = String2Float(40.23578);
float My_new_float = String2Float("40.23578");
// returns 40.235780
// returns 40.235780


float My_new_float = String2Float(-683.3);
float My_new_float = String2Float("-683.3");
// returns -683.300000
// returns -683.300000


float My_new_float = String2Float(9924);
float My_new_float = String2Float("9924");
// returns 9924.000000
// returns 9924.000000
</lsl>
</lsl>

Revision as of 22:21, 22 July 2012

Summary

Function: float String2Float( string str );

Returns a float that will be signed if negative.

• string str string to be typecast to a float

The number str provided as a string may be negative and may or may not have a decimal point
Returns 0.000000 if the string contains non-numerical characters (other than a negative sign or a decimal point).

Example: <lsl> float My_new_float = String2Float("40.23578"); // returns 40.235780

float My_new_float = String2Float("-683.3"); // returns -683.300000

float My_new_float = String2Float("9924"); // returns 9924.000000 </lsl>

Specification

<lsl>float String2Float(string ST) {

   list nums = ["0","1","2","3","4","5","6","7","8","9",".","-"];
   float FinalNum = 0.0;
   integer idx = llSubStringIndex(ST,".");
   if (idx == -1)
   {
       idx = llStringLength(ST);
   }
   integer Sgn = 1;
   integer j;
   for (j=0;j< llStringLength(ST);j++)
   {
       string Char = llGetSubString(ST,j,j);
       if (~llListFindList(nums,[Char]))
       {
           if((j==0) && (Char == "-"))
           {
               Sgn = -1;
           }
           else if (j < idx)
           {
               FinalNum = FinalNum + (float)Char * llPow(10.0,((idx-j)-1));
           }
           else if (j > idx)
           {
               FinalNum = FinalNum + (float)Char * llPow(10.0,((idx-j)));
           }
       }
   }
   return FinalNum * Sgn;

} </lsl>

Examples