CherryPicker
CherryPicker

Reputation: 11

Substitute character for integer

I am working on a project where I need to find the integer value substituted from a character which is either 'K' 'M' or 'B'. I am trying to find the best way for a user to input a string such as "1k" "12k" "100k" and to receive the value back in the appropriate way. Such as a user entering "12k" and I would receive "12000".

I am new to Lua, and I am not that great at string patterns.

if (string.match(text, 'k')) then
  print(text)
  local test = string.match(text, '%d+')
  print(test)
end 

Upvotes: 1

Views: 119

Answers (2)

Piglet
Piglet

Reputation: 28954

local text = "1k"
print(tonumber((text:lower():gsub("[kmb]", {k="e3"}))))

I don't know what factors you use for M and B. What is that supposed to be? Million and billion?

I suggest you use the international standard. kilo (k), mega (M), giga (G) instead.

Then it would look like so:

 local text = "1k"
 print(tonumber((text:gsub("[mkMG]", {m = "e-3", k="e3", M="e6", G="e9"}))))  --and so on

Upvotes: 3

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7064

You can match the pattern as something like (%d+)([kmb]) to get the number and the suffix separately. Then just tonumber the first part and map the latter to a factor (using a table, for example) and multiply it with your result.

local factors = { k=1e3, m=1e6, --[and so on]] }
local num, suffix = string.match(text, '(%d+)([kmb])')
local result = tonumber(num) * factors[suffix]

Upvotes: 2

Related Questions