Difference between revisions of "Float2String"

From Second Life Wiki
Jump to navigation Jump to search
(cleaned up source)
Line 38: Line 38:
     return (string)num;
     return (string)num;
}</lsl>
}</lsl>
|deepnotes=Inspired by (and evolved from) discussions between {{User|Cheree Bury}} & {{User|Domino Marama}} in the SL Scripting Forum July 2008 at http://forums.secondlife.com/showthread.php?t=267884, with optional rounding added (that part being inspired by work by various authors here: [[Fixed_Precision]] )
|deepnotes=Inspired by (and evolved from) discussions between {{User|Cheree Bury}} & {{User|Domino Marama}} in the SL Scripting Forum July 2008 at http://forums-archive.secondlife.com/54/15/267884/1.html, with optional rounding added (that part being inspired by work by various authors here: [[Fixed_Precision]] )
|cat1=Examples
|cat1=Examples
}}
}}

Revision as of 04:32, 9 April 2010

Summary

Function: string Float2String( float num, integer places, integer rnd );

Returns a string that contains the float num in a tidy text format, with optional rounding.

• float num number to be formatted
• integer places number of places to use during formatting
• integer rnd boolean, enables/disables rounding

Negative floats are fine (i.e. negative signs will be preserved.)
If you say 1 place, you will get 7.0 instead of 7.0000000
If you say 3 places, you get 7.14 instead of 7.1400000
7.1373699 will come out as 7.13 or 7.14, depending on whether you specify rounding
rnd (rounding) should be set to TRUE for Rounding, FALSE for no rounded

Example:

string myFormattedFloat = Float2String(-7.1373699, 3, TRUE);
//rounded returns -7.14

string myFormattedFloat = Float2String(-7.1373699, 3, FALSE);
//not rounded returns -7.13

Specification

<lsl>string Float2String ( float num, integer places, integer rnd) { //allows string output of a float in a tidy text format //rnd (rounding) should be set to TRUE for rounding, FALSE for no rounding

   if (rnd) {
       float f = llPow( 10.0, places );
       integer i = llRound(llFabs(num) * f);
       string s = "00000" + (string)i; // number of 0s is (value of max places - 1 )
       if(num < 0.0)
           return "-" + (string)( (integer)(i / f) ) + "." + llGetSubString( s, -places, -1);
       return (string)( (integer)(i / f) ) + "." + llGetSubString( s, -places, -1);
   }
   if (!places)
       return (string)((integer)num );
   if ( (places = (places - 7 - (places < 1) ) ) & 0x80000000)
       return llGetSubString((string)num, 0, places);
   return (string)num;

}</lsl>

Examples

Deep Notes

Inspired by (and evolved from) discussions between Cheree Bury & Domino Marama in the SL Scripting Forum July 2008 at http://forums-archive.secondlife.com/54/15/267884/1.html, with optional rounding added (that part being inspired by work by various authors here: Fixed_Precision )

Signature