javascript - how to prevent toFixed from rounding off decimal numbers

前端 未结 5 1443
栀梦
栀梦 2020-11-28 14:29

I\'m very new to html, javascript, and css so please forgive if my question sounds idiotic to you. My question is how can I prevent the function toFixed() from

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 15:23

    That's even simpler:

    function truncateToDecimals(num, dec = 2) {
      const calcDec = Math.pow(10, dec);
      return Math.trunc(num * calcDec) / calcDec;
    }
    

    So:

    truncateToDecimals(123456.786) -> 123456.78
    

提交回复
热议问题