3. 求餘方法(修訂)
4. 總結:
自從有了markdown,陸續把一些部落格搬到這裡來了~
time:2015/04/21
function getprecisedecimal(nnum, n)
if type(nnum) ~= "number" then
return nnum;
endn = n or 0;
n = math.floor(n)
local fmt = '%.' .. n .. 'f'
local nret = tonumber(string.format(fmt, nnum))
return nret;
end
後記:2015/06/25
string.format("%.xf", nnum)會對nnum進行四捨五入(同c語言中的printf的格式符一樣)。所以這種方法也是有問題的,用的人請注意
舉例:
1. getprecisedecimal(0.38461538461538) = 0.4
function getprecisedecimal(nnum, n)
if type(nnum) ~= "number" then
return nnum;
endn = n or 0;
n = math.floor(n)
if n < 0 then
n = 0;
endlocal ndecimal = 1/(10 ^ n)
if ndecimal == 1 then
ndecimal = nnum;
endlocal nleft = nnum % ndecimal;
return nnum - nleft;
end
結果:
2. getprecisedecimal(0.38461538461538) = 0.3
問題:在lua下面,存在0.7 % 0.1 = 0.1的情況,所以上面寫法錯誤
舉例:
2. getprecisedecimal(0.7) = 0.6
解決:見3.修訂,不使用求餘方法
function getprecisedecimal(nnum, n)
if type(nnum) ~= "number" then
return nnum;
endn = n or 0;
n = math.floor(n)
if n < 0 then
n = 0;
endlocal ndecimal = 10 ^ n
local ntemp = math.floor(nnum * ndecimal);
local nret = ntemp / ndecimal;
return nret;
end
測試:
3. getprecisedecimal(0.38461538461538) = 0.7
3. getprecisedecimal(0.7) = 0.7
待測:不知道還有沒有其他問題 C 小數保留N位
1.使用 system.globalization.numberformatinfo system.globalization.numberformatinfo provider new system.globalization.numberformatinfo provider.numberdec...
Lua中保留兩位小數
在使用lua進行開發的時候,經常會遇到保留n位小數的問題,這裡以保留兩位小數為例,記錄一下需要注意的地方!在選擇處理方案之前,首先要確認需求,搞清楚保留兩位小數是指小數點後第三位四捨五入還是從小數點後第三位開始直接捨去!小數點後第三位四捨五入 string.format 2f num local n...
C 輸出保留 n 位小數或者精度
保留兩位有效數字 因為c 是相容 c 語言的,所以可以直接使用 c 語言的printf語句,方法是新增乙個 include 或者 include 然後使用 printf 2f floatnum 當然 c 也有自己的處理方式,那就是 include cout setiosflags ios fixed...