Really dumb question i guess

Posted by AquaBrother on Tue 11 Jun 2013 02:09 AM — 4 posts, 16,278 views.

Brazil #0
Hi guys, i've been trying to do something which i think might be pretty easy to solve but yet i'm strugling to do it...

Here we go, i have a number for example:

1500700

Thing is i wanted to make something in order to separate that with dots to output something like:

1.500.700 (like a normal number separation)

I was trying to work with string.gsub and string.sub together and alone but i coundnt think on something to solve that...

You guys are my last hope cuz i give up.

Thx in advance.
Australia Forum Administrator #1
There is an inbuilt module "commas" that does that:


require "commas"

print (commas ("1500700"))


Result:


1,500,700


You could edit that to change the comma to a dot, or do a string replace, eg.


require "commas"

print ((string.gsub (commas ("1500700"), ",", ".")))


Output:


1.500.700
Australia Forum Administrator #2
The function itself is pretty small:


--[[

Commas in numbers

This function adds commas to big numbers. 
For example 123456 becomes "123,456".

--]]

-- ----------------------------------------------------------

function commas (num)
  assert (type (num) == "number" or
          type (num) == "string")
  
  local result = ""

  -- split number into 3 parts, eg. -1234.545e22
  -- sign = + or -
  -- before = 1234
  -- after = .545e22

  local sign, before, after =
    string.match (tostring (num), "^([%+%-]?)(%d*)(%.?.*)$")

  -- pull out batches of 3 digits from the end, put a comma before them

  while string.len (before) > 3 do
    result = "," .. string.sub (before, -3, -1) .. result
    before = string.sub (before, 1, -4)  -- remove last 3 digits
  end -- while

  -- we want the original sign, any left-over digits, the comma part,
  -- and the stuff after the decimal point, if any
  return sign .. before .. result .. after

end -- function commas


In the middle change the comma to a period if you want a different separator.
Brazil #3
I knew there was a magical command, rofl...

Thx again Nick, you're awesome...

Really appreciate the help...

Best regards...