將浮點數除以 4,四捨五入為 2 個小數點,然後計算 JavaScript 中的餘數


假設我們有一個浮點數 −

2.74

如果我們將此數字除以 4,則結果為 0.685。

我們要將此數字除以 4,但應將結果四捨五入為 2 個小數點。

因此,結果應該是 −

3 times 0.69 and a remainder of 0.67

示例

程式碼如下 −

const num = 2.74;
const parts = 4;
const divideWithPrecision = (num, parts, precision = 2) => {
   const quo = +(num / parts).toFixed(precision);
   const remainder = +(num - quo * (parts - 1)).toFixed(precision);
   if(quo === remainder){
      return {
         parts,
         value: quo
      };
   }else{
      return {
         parts: parts - 1,
         value: quo,
         remainder
      };
   };
};
console.log(divideWithPrecision(num, parts));

輸出

控制檯中的輸出為 −

{ parts: 3, value: 0.69, remainder: 0.67 }

更新於:2020-11-20

728 次瀏覽

開啟你的 職業生涯

完成課程來獲取認證

開始
廣告