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

Rounding

Started by Aggermor, 29 March 2015 - 06:06 PM
Aggermor #1
Posted 29 March 2015 - 08:06 PM
I wrote a piece of code that has a very large decimal remainder that I dont want to she when I print the value.


print(math.floor(power/100000).."%")

When it prints it returns "87.0%"

How can I remove the ".0" decimal? (Round to the nearest whole number)

I tried using

print(math.abs(power/100000).."%")
but that didnt work either, it return the whole number with even rounding.
Geforce Fan #2
Posted 29 March 2015 - 08:48 PM
string.gsub(tostring(number),".0","")
number = tonumber(number)
Dog #3
Posted 29 March 2015 - 08:56 PM
You just need to convert the number to a string when writing it to screen so CC doesn't add the .0 at the end, like so…

print(tostring(math.floor(power/100000)) .. "%")
Aggermor #4
Posted 29 March 2015 - 09:00 PM
You just need to convert the number to a string when writing it to screen so CC doesn't add the .0 at the end, like so…

print(tostring(math.floor(power/100000)) .. "%")

Perfect! This worked thanks! I have never messed with a string before and I'm not even sure what it is but it worked so thank you!
Bomb Bloke #5
Posted 29 March 2015 - 11:31 PM
Long story short, strings can contain a series of characters in a row. "Stringed together", these characters can form words, sentences, and so on - so the data type is called a string, and you'll've actually used them a lot before now. See this guide for more info on data types.

When you go to print a number, you typically want the value to be converted from the base-two value in your computer's RAM into a string first. There are lots of different ways to format the new string, and print() will tend to add the decimal on the end if you pass the number directly to it and expect it to handle the conversion on its own (even if the number could be presented as an integer). If you pre-convert with tostring(), the decimal gets chopped off where possible.
MKlegoman357 #6
Posted 30 March 2015 - 12:55 AM
…and print() will tend to add the decimal on the end if you pass the number directly to it and expect it to handle the conversion on its own (even if the number could be presented as an integer).

The print() function uses tostring() internally, so it's not actually preserving the decimal. The concat operator is the one to blame in OP's code.
Edited on 29 March 2015 - 10:56 PM
Bomb Bloke #7
Posted 30 March 2015 - 01:49 AM
Ah! Good point - that operation gets performed before the print() function actually gets called. Silly me!