Author Topic: sefun for adding commas to an integer  (Read 2903 times)

Offline llyr

  • Pottymouth
  • *
  • Posts: 1
    • View Profile
sefun for adding commas to an integer
« on: October 23, 2006, 09:11:16 PM »
Mudlib: Dead Souls 2.1.1

Driver: ShazbotOS v0.1.2/MudOS v22.2b14



What follows is a simulated efun for taking an integer and creating a grouped-by-commas string representation of it. I'm sure there's better terminology for this concept, but the basic idea is to take 1234567 and turn it into "1,234,567".





code:

string comma_int(int i)
{
  int power = 0;
  int tmp = 0;
  string output = "";

  power = to_int(log(i) / log(10));

  while(power) {
    tmp = to_int(pow(10, power));
    output += itoa(i / tmp);
    if ((power > 0) && ((power % 3) == 0))
      output += ",";
    i -= i / tmp * tmp;
    power--;
  }
  output += itoa(i);

  return output;
}




The above was modified to incorporate Jimorie's log() advice as well as fix the bug noticed by Daelas. Thanks folks!

Offline capo

  • Friend
  • **
  • Posts: 70
    • View Profile
sefun for adding commas to an integer
« Reply #1 on: October 23, 2006, 09:41:45 PM »
This works wonderfully in my modified ds2.1!

Offline daelaskai

  • BFF
  • ***
  • Posts: 174
    • View Profile
sefun for adding commas to an integer
« Reply #2 on: October 23, 2006, 10:08:20 PM »

I noticed that it does not work for numbers such as 1000 even though it works fine for 2000.  Just an observation.



Daelas


Offline Jimorie

  • Friend
  • **
  • Posts: 58
    • View Profile
sefun for adding commas to an integer
« Reply #3 on: October 24, 2006, 02:09:13 AM »
Looks like a handy function if you are in the business of displaying large integers to the player. I would however suggest you take a look at the log() efun (I just checked, your MudOS should have one). Instead of looping pow() to find out the power, just do this:



power = log(i) / log(10);


You might have to cast the result to an integer, but I think MudOS will do that for you.



I will post an alternative solution that doesn't bother with pow() or log() at all, which I would think is simpler. According to the forum rules I have to post this in a separate thread, so I'll do that even though I don't really see the point. I am not here to bash Llyr's code, just to provide another approach. See this thread: http://lpmuds.net/forum/index.php?webtag=LPC&msg=179.1">http://lpmuds.net/forum/index.php?webtag=LPC&msg=179.1

Offline detah

  • BFF
  • ***
  • Posts: 190
  • Ruler of 2D
    • View Profile
sefun for adding commas to an integer
« Reply #4 on: October 24, 2006, 06:27:00 AM »

Thank you guys.  

I was going to address this sooner or later myself.

Im kinda surprised this functionality doesnt already exist in the driver code.