參考資料 ----
當 整數遇上浮點數時,其運算結果往往是預期之外,目前可借助 第三方函式庫(或該說是 類別庫?) Decimal() 來維持 浮點數 與 整數的 混合運算 的精度。
簡單來說就是將每個數都轉換為 Decimal 類別,再進行運算。
這個函式庫採 MIT 授權,並開放原始碼,放在 GitHub,去官網下載後,上傳到您網站的指定目錄,例如:/js/ 下
<script src='/js/decimal.js'></script>
...
...
<script>
ii = 9999
fPlate1 = Decimal(parseInt(ii)/80); // 124.9875
fPlate2 = Decimal(Math.floor(parseInt(sPlate)/80)); // 9999 ÷ 80 的整數 = 124
fPlate3 = fPlate1.minus(fPlate2); // 124.9875 - 124 = 0.9875
iPlate4 = fPlate3.times(80); // 0.9875 × 80 = 79
// 注意:上述的數字都是 Decimal 類別
// 必須轉換為 int 才能進行 switch()
switch(parseInt(iPlate4))
{
case 1: ...
break;
case 2: ...
break;
...
}
...
...
</script>
沒有留言:
張貼留言