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

Decimals

Started by vrtMC, 25 June 2016 - 08:27 PM
vrtMC #1
Posted 25 June 2016 - 10:27 PM
Hi there,

I know this has been answered before. And I also looked it up at different forums, but apparently Im missing something.

So, this is the code Im using:

local eustored = mfsu.getEUStored()
perc = eustored / mfsu.getEUCapacity() * 100
term.write(string.format("%.2f", perc).. " %")

Im trying to get "perc" written as a 2 decimal number, but it looks like its not formatting the number in anyway. As far as Im aware Im doing exactly what the tutorials/examples write. So, what am I doing wrong?
KingofGamesYami #2
Posted 25 June 2016 - 10:46 PM
string.format is broken in LuaJ, which CC uses. Instead, use string.match, or string.sub.

term.write( perc:match( "(%d+%.%d?%d?)" ) )

https://github.com/dan200/ComputerCraft/issues/91
Edited on 25 June 2016 - 08:47 PM
vrtMC #3
Posted 26 June 2016 - 02:45 AM
Right, ok.

I tried the code you gave me and that didnt work, so been looking around abit for the string.match-syntax.

Changed it to:

term.write(string.match(perc, "%d+%.%d?%d?").. "%")

That did the job.

Thanks for the heads up.
KingofGamesYami #4
Posted 26 June 2016 - 03:02 AM
I don't see why it wouldn't work, I tested it in-game myself. Weird.
vrtMC #5
Posted 26 June 2016 - 03:39 PM
If I remember correctly it gave an attempt to index ? (a nil value)-error. I was kinda surprised by that since its not going through a list.
KingofGamesYami #6
Posted 26 June 2016 - 04:25 PM
Well, if the variable 'perc' was nil, that's what I would expect.
vrtMC #7
Posted 26 June 2016 - 04:34 PM
But if that was the case then the change I made in the code still would give that error, right?
KingofGamesYami #8
Posted 26 June 2016 - 09:34 PM
No, because my example indexes the string; yours does not. If anything, your example would error differently.
EditOh I see what happened. You got "Attempt to index ? (a number value)". That I would expect, I think string.match tostring's it for you in your example.
Edited on 26 June 2016 - 07:37 PM
vrtMC #9
Posted 26 June 2016 - 11:31 PM
Uh yes, now you mention that one Im pretty sure it was that exact error.

Im still trying to wrap my head around the string.match-syntax though. All the character classes you can use make it pretty complicated.
Edited on 26 June 2016 - 09:38 PM
DvgCraft #10
Posted 27 June 2016 - 02:22 PM
If you want to round the number down at 2 decimals, you could also use this (if you still need it):

term.write( math.floor(perc*100)/100 .."%" )
(notice the space between 100 and .."%". It's important)
vrtMC #11
Posted 27 June 2016 - 05:35 PM
Thanks for the suggestion, I already got it working with the string.match-function though.