How do I remove point symbol from the decimal number?

Viewed 57

I'm trying to take decimal number as an input and I need output of all numbers but without the point symbol in it.

Example input: 123.4

Wanted output 1234

The problem I have that when converting decimal number into string and trying to remove "." using :gsub('%.', '') its removing the point symbol but outputs 1234 1 . I have tried :gsub('.', '') as well but it outputs 5. I'm clueless where those numbers come from, here is the screenshot:

enter image description here

2 Answers

Use this syntax to get what you want and discard/ignore what you dont need...

local y = 123.4

-- Remove decimal point or comma here
local str, matches = tostring(y):gsub('[.,]', '')
-- str holds the first return value
-- The second return value goes to: matches

-- So output only the string...
print(str) -- Output: 1234

-- Or/And return it...
return str

There are two issues at play here:

  1. string.gsub returns two values, the resulting string and the number of substitutions. When you pass the results of gsub to print, both will be printed. Solve this by either assigning only the first return value to a variable (more explicit) or surrounding gsub with parenthesis.
  2. . is a pattern item that matches any character. Removing all characters will leave you with the empty string; the number of substitutions - 5 in your example - will be the number of characters. To match the literal dot, either escape it using the percent sign (%.) or enclose it within a character set ([.]), possibly adding further decimal separators ([.,] as in koyaanisqatsi's answer).

Fixed code:

local y = 123.4
local str = tostring(y):gsub("%.", "") -- discards the number of substitutions
print(str)

this is unreliable however since tostring guarantees no particular output format; it might as well emit numbers in scientific notation (which it does for very large or very small numbers), causing your code to break. A more elegant solution to the problem of shifting the number such that it becomes an integer would be to multiply the number by 10 until the fractional part becomes zero:

local y = 123.4
while y % 1 ~= 0 do y = y * 10 end
print(y) -- note: y is the number 1234 rather than the string "1234" here
Related