13 posts
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?
3057 posts
Location
United States of America
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
13 posts
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.
3057 posts
Location
United States of America
Posted 26 June 2016 - 03:02 AM
I don't see why it wouldn't work, I tested it in-game myself. Weird.
13 posts
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.
3057 posts
Location
United States of America
Posted 26 June 2016 - 04:25 PM
Well, if the variable 'perc' was nil, that's what I would expect.
13 posts
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?
3057 posts
Location
United States of America
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
13 posts
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
14 posts
Location
The Netherlands
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)
13 posts
Posted 27 June 2016 - 05:35 PM
Thanks for the suggestion, I already got it working with the string.match-function though.