Float2String

From Second Life Wiki
Revision as of 11:47, 12 July 2008 by Chaz Longstaff (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

Allows string output of a float in a tidy text format, with optional 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 "Rounded" for Yes, "" for not rounded

Example:

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

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


Specification

<lsl>string Float2String ( float num, integer places, string rnd) { //allows string output of a float in a tidy text format //rnd (rounding) should be set to "Rounded" for Yes, "" for not rounded

   string neg = "";
   if (num < 0.0) neg = "-";
   if (places == 0) {
       return neg + (string) ((integer)num );
   }
   else if (rnd != "Yes") {
       if ( (places = (places - 7 - (places < 1) ) ) & 0x80000000) {
           return llGetSubString((string)num, 0, places);
       }
       return (string)num;
   }
   else {
       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);
   }

}</lsl>

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: https://wiki.secondlife.com/wiki/Fixed_Precision )