z_mirror/flib
git clone https://git.raiguard.me/z_mirror/flib
a9f2be7
trunk
1--- Various string formatting functions. 2--- ```lua 3--- local flib_format = require("__flib__.format") 4--- ``` 5--- @class flib_format 6local flib_format ={} 7 8local suffix_list ={ 9{ "Q" , 1e30 } , -- quetta 10{ "R" , 1e27 } , -- ronna 11{ "Y" , 1e24 } , -- yotta 12{ "Z" , 1e21 } , -- zetta 13{ "E" , 1e18 } , -- exa 14{ "P" , 1e15 } , -- peta 15{ "T" , 1e12 } , -- tera 16{ "G" , 1e9 } , -- giga 17{ "M" , 1e6 } , -- mega 18{ "k" , 1e3 } , -- kilo 19} 20 21--- Format a number for display, adding commas and an optional SI suffix. 22--- Specify `fixed_precision` to display the number with the given width, 23--- adjusting precision as necessary. 24--- @param amount number 25--- @param append_suffix boolean? 26--- @param fixed_precision number? 27--- @return string 28function flib_format . number ( amount , append_suffix , fixed_precision ) 29local suffix ="" 30if append_suffix then 31for _ , data in ipairs ( suffix_list ) do 32if math . abs ( amount ) >= data [ 2 ] then 33amount =amount / data [ 2 ] 34suffix =" " .. data [ 1 ] 35break 36end 37end 38if not fixed_precision then 39amount =math . floor ( amount * 10 ) / 10 40end 41end 42local formatted , k =tostring ( amount ), nil 43if fixed_precision then 44-- Show the number with fixed width precision 45local len_before =# tostring ( math . floor ( amount )) 46local len_after =math . max ( 0 , fixed_precision - len_before - 1 ) 47formatted =string . format ( "%." .. len_after .. "f" , amount ) 48end 49-- Add commas to result 50while true do 51formatted , k =string . gsub ( formatted , "^(-?%d+)(%d%d%d)" , "%1,%2" ) 52if k == 0 then 53break 54end 55end 56return formatted .. suffix 57end 58 59--- Convert the given tick or game.tick into "[hh:]mm:ss" format. 60--- @param tick uint? 61--- @param include_leading_zeroes boolean? 62--- @return string 63function flib_format . time ( tick , include_leading_zeroes ) 64local total_seconds =math . floor (( tick or game . ticks_played ) / 60 ) 65local seconds =total_seconds % 60 66local minutes =math . floor ( total_seconds / 60 ) 67if minutes > 59 then 68minutes =minutes % 60 69local hours =math . floor ( total_seconds / 3600 ) 70if include_leading_zeroes then 71return string . format ( "%02d:%02d:%02d" , hours , minutes , seconds ) 72else 73return string . format ( "%d:%02d:%02d" , hours , minutes , seconds ) 74end 75else 76if include_leading_zeroes then 77return string . format ( "%02d:%02d" , minutes , seconds ) 78else 79return string . format ( "%d:%02d" , minutes , seconds ) 80end 81end 82end 83 84return flib_format