Difference between revisions of "String2Float"
Jump to navigation
Jump to search
(... why does this exist? It is faster and eaiser to just use (float)"float value") |
m (<lsl> tag to <source>) |
||
Line 9: | Line 9: | ||
'''Example:''' | '''Example:''' | ||
< | <source lang="lsl2"> | ||
float My_new_float = String2Float("40.23578"); | float My_new_float = String2Float("40.23578"); | ||
// returns 40.235780 | // returns 40.235780 | ||
Line 18: | Line 18: | ||
float My_new_float = String2Float("9924"); | float My_new_float = String2Float("9924"); | ||
// returns 9924.000000 | // returns 9924.000000 | ||
</ | </source> | ||
|spec=< | |spec=<source lang="lsl2">float String2Float(string ST) | ||
{ | { | ||
list nums = ["0","1","2","3","4","5","6","7","8","9",".","-"]; | list nums = ["0","1","2","3","4","5","6","7","8","9",".","-"]; | ||
Line 51: | Line 51: | ||
return FinalNum * Sgn; | return FinalNum * Sgn; | ||
} | } | ||
</ | </source> | ||
|deepnotes= | |deepnotes= | ||
|cat1=Examples | |cat1=Examples | ||
}} | }} |
Latest revision as of 17:07, 24 January 2015
LSL Portal | Functions | Events | Types | Operators | Constants | Flow Control | Script Library | Categorized Library | Tutorials |
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:
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
Specification
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;
}