爲什麼10000000000000.126.toString()
1000000000000.127和100000000000.126.toString()
不是?爲什麼10000000000000.126.toString()1000000000000.127(以及我能做些什麼來防止它)?
我認爲它必須與Js中一個數字的最大值有關(按照this SO question),但是這與浮點運算有關嗎?
我在問,因爲我寫了這個函數來使用數千個分隔符來格式化一個數字,並且想要阻止這個。
function th(n,sep) {
sep = sep || '.';
var dec = n.toString().split(/[,.]/),
nArr = dec[0].split(''),
isDot = /\./.test(sep);
return function tt(n) {
return n.length > 3 ?
tt(n.slice(0,n.length-3)).concat(n.slice(n.length-3).join('')) :
[n.join('')]
;
}(nArr)
.join(sep)
+ (dec[1] ? (isDot?',':'.') + dec[1] : '');
}
sep1000(10000000000000.126); //=> 10.000.000.000.000,127
sep1000(1000000000000.126); //=> 1.000.000.000.000,126
這是因爲我們的老朋友浮點精度。 – deceze
[爲什麼C浮點類型修改輸出的實際輸入125.1到125.099998?](http://stackoverflow.com/questions/6532502/why-does-ac-floating-point-type-modify - 實際輸入125-1至125-099998-o)和**許多其他** – Alnitak
@Alnitak,我知道,但另外我正在尋找一種方法來防止它。我仍然在尋找相關的答案,真的。 – KooiInc