This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
GamerNebulae's profile picture

[SOLVED] String manipulation (Solution in post)

Started by GamerNebulae, 25 June 2014 - 07:12 PM
GamerNebulae #1
Posted 25 June 2014 - 09:12 PM
Hello everyone!

I am trying to shorten a long number (e.g. 12 308 129 becomes 12.3M). I have read about the gsub functionality, but I was wondering, how do these iterators and patterns work?

EDIT: Or at least tell me what kind of iterator and pattern I would need to turn a number (in this case, divided by a million) with alot of decimals into a compact, 1 decimal number.
Edited on 25 June 2014 - 09:54 PM
CometWolf #2
Posted 25 June 2014 - 11:10 PM
There's no need for anything fancy to deal with that really. Just use string.sub.

local function oneDecimal(number,decimalPoint)
  number = string.format(number) --convert to string format
  local decimal = number:sub(decimalPoint,decimalPoint)
  return number:sub(1,decimalPoint-1).."."..decimal
end
string.sub returns the symbols of a string in the given range, ie string.sub("hello",1,4) would return "hell".
GamerNebulae #3
Posted 25 June 2014 - 11:54 PM
-snip-

Thanks for the push in the right direction! :)/> This is how I fixed it:

function shorten(amount)
    print(string.sub(tostring(amount), 1, string.find(tostring(amount), "%p") + 1))
end