Lua time conversion and numbers retain the specified number of decimal places

Summarize the recent misunderstandings, about the use of time and timestamp conversion and about lua retaining the specified number of decimal places,

The first is time conversion.

-- 转换成时间 【xxx小时xxx分xxx秒】 单位秒
function TimeUtil:FormatTimeString(time)
    if time and time >= 0 then
        local tb = {
    
    }
        tb.day = math.floor(time / 60 / 60 / 24)
        tb.hour = math.floor(time / 3600) % 24
        tb.min = math.floor(time / 60) % 60
        tb.sec = math.floor(time % 60)
        return tb
    end
end

This is suitable for calculating the time difference and then counting down.

---FormatTimeSpanToDate
---@param timeSpan number 10位的时间戳
function TimeUtil:FormatTimeSpanToDate(timeSpan)
    if timeSpan and timeSpan >= 0 then
        local tb = {
    
    }
        tb.year = tonumber(os.date("%Y",timeSpan))
        tb.mon =tonumber(os.date("%m",timeSpan))
        tb.day = tonumber(os.date("%d",timeSpan))
        tb.hour = tonumber(os.date("%H",timeSpan))
        tb.min = tonumber(os.date("%M",timeSpan))
        tb.sec = tonumber(os.date("%S",timeSpan))
        return tb
    end
end

This is the time stamp converted into year, month and day, suitable for displaying the date

--时间戳格式化
os.date("%Y-%m-%d %H:%M:%S", os.time())
--2022-02-11 16:22:24
os.date("%m月%d日%H:%M:%S", os.time())
--02月11日16:22:24
os.date("%Y%m%d%H%M%S",os.time())
--20220211162224

About lua retaining the specified decimal

--lua原本提供的保留n位小数的方法。此方法的误区在于保留时遵循四舍五入的原则。
--即 0.111显示为 0.11, 0.116显示为 0.12
string.format("%.2f", num)

The above reservations apply to most problem solutions. However, there will be such a problem on the display page of the combat power data we have made. Under special circumstances, the sum of the combat power of different modules will be greater than the total combat power data, which is easier to be misunderstood.
So a solution to take the value down is needed. That is, the data corresponding to the number of digits can be intercepted.

--- 截取指定位数的数据
--- nNum 源数字
--- n 小数位数
function GameUtil:CustomFormatNum(nNum, n)
    if type(nNum) ~= "number" then
        return nNum
    end
    n = n or 0
    n = math.floor(n)
    if n < 0 then
        n = 0
    end
    local nDecimal = 10 ^ n
    local nTemp = math.floor(nNum * nDecimal)
    local nRet = nTemp / nDecimal
    return nRet
end

that's all.

Guess you like

Origin blog.csdn.net/qq_39860954/article/details/122882531