Jump to content

string.gsub - cuestion


Cocodrilo

Recommended Posts

I use :

local money = getPlayerMoney(getLocalPlayer()) 
string.gsub(money,"^(-?%d+)(%d%d%d)", '%1,%2') 

When money is

1 000 = 1,000

10 000 = 10,000

100 000 = 100,000

etc.

But When money is 1 000 000 returns 1000,000. How i get 1,000,000 ? *without modifying the previous examples

Link to comment

Use comma_value function for that.

local money = getPlayerMoney(getLocalPlayer()) 
local formattedMoney = comma_value(money) 
  
-- from [url=http://lua-users.org/wiki/FormattingNumbers]http://lua-users.org/wiki/FormattingNumbers[/url] 
function comma_value(amount) 
  local formatted = amount 
  while true do   
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') 
    if (k==0) then 
      break 
    end 
  end 
  return formatted 
end 

Link to comment

Alternate version with no loops.

function commaNumber(n) 
    local left, num, right = string.match(n, "^([^%d]*%d)(%d*)(.-)$") 
    return left..(num:reverse():gsub("(%d%d%d)", "%1,"):reverse())..right 
end 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...