float2String

From Second Life Wiki
Revision as of 07:19, 18 September 2008 by Strife Onizuka (talk | contribs)
Jump to navigation Jump to search

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

   string neg = "";
   if (num < 0.0) neg = "-";
   if (places == 0) {
       return neg + (string) ((integer)num );
   }
   else 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 )
       return neg + (string)( (integer)(i / f) ) + "." + llGetSubString( s, -places, -1);
   }
   else {
       if ( (places = (places - 7 - (places < 1) ) ) & 0x80000000) {
           return llGetSubString((string)num, 0, places);
       }
       return (string)num;
   }
   else

}</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.secondlife.com/showthread.php?t=267884, with optional rounding added (that part being inspired by work by various authors here: Fixed_Precision )

Signature