string2Float

From Second Life Wiki
Revision as of 15:42, 22 July 2012 by Rolig Loon (talk | contribs) (Created page with "{{LSL Function |func=String2Float |mode=user |p1_type=string|p1_name=str|p1_desc=string to be typecast to a float |return_type=float |return_text=that will be signed if negative.…")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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

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