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

Need help reducing a float to two decimal places

Started by xxwalgreensxx, 16 February 2016 - 02:12 AM
xxwalgreensxx #1
Posted 16 February 2016 - 03:12 AM
Hey all!

I am playing on the relatively new modpack Tekkit Legends and I am coding an API and a control program that uses it for the Big Reactors mod which is part of the pack. Right now the control program only functions as a remote display for my reactor, but that is where I am having trouble. I am using the computer port from big reactors to get data from the reactor itself and certain methods return float values that have an incredibly long decimal, which I would like to reduce to two decimal places because it will not fit on the monitor I am using to display the info plus it is really messy looking. So far I have tried using string.format() with little success, the values it returns are either not formatted or inconsistantly formatted to an arbitrary number of decimal points that changes nearly every time my display updates itself. If necessary I can post my API and program.

Thanks to everyone in advance!
Bomb Bloke #2
Posted 16 February 2016 - 04:03 AM
I've got a vague memory string.format()'s a bit busted. Never played with it much myself. I'd do something like this:

math.floor(value * 100) / 100
Dragon53535 #3
Posted 16 February 2016 - 09:08 AM

string.format("%.2f",str)
%.02f says replace this with a floating point number (f) with 2 decimal places padded with 0's. 10.00, 12.57.

Edit: I'm wrong, looking for actual format

Edit 2: Found the correct way to format it. Note though it does not round, it truncates. Truncation is where the rest of the decimal places are cut off of the end. 25.64267 could be truncated to be 25 or 25.242 or whatever, it does not round at all.
Edited on 16 February 2016 - 08:30 AM
xxwalgreensxx #4
Posted 16 February 2016 - 05:46 PM
math.floor(value * 100) / 100

This worked perfectly, thank you so much!