7 posts
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.
1029 posts
Location
Missouri, United States, America, Earth, Solar System, Milky Way, Universe 42B, Life Street, Multiverse, 4th Dimension
Posted 29 March 2015 - 08:48 PM
string.gsub(tostring(number),".0","")
number = tonumber(number)
1220 posts
Location
Earth orbit
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)) .. "%")
7 posts
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!
7083 posts
Location
Tasmania (AU)
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.
1140 posts
Location
Kaunas, Lithuania
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
7083 posts
Location
Tasmania (AU)
Posted 30 March 2015 - 01:49 AM
Ah! Good point - that operation gets performed before the print() function actually gets called. Silly me!