0

I have the number 0.6720505101642719 I would like to make It 0.6720 while .toFixed(4) returns 0.6721 and slicing the number as string won't work as well

const modifyDecimal = (number, decimalCount) => {
  const parts = number.toString().split('.');
  const limitedDecimal = parts[1].slice(0, decimalCount);

  return Number(`${parts[0]}.${limitedDecimal}`);
}

modifyDecimal(0.6720505101642719, 4)
// 0.672 missing the 0 here
Ilanus
  • 6,690
  • 5
  • 13
  • 37
  • Well, `0.672 === 0.6720`. You can't get it to stay in memory as "0.6720" you're going to have to do some formatting to get that exact precision. – gabriel.hayes Nov 08 '19 at 18:31

4 Answers4

0

Use this:

Math.makeShorter = function(number, decimals) {
        if(decimals < 1) return Math.floor(number).toString();
        var factor =  Math.pow(10, decimals);
        var num = Math.floor(number);
        var fraction = (Math.floor((number - num) * factor) / factor).toString().split('.').pop().toString();
        var digits = fraction.length;
        if(digits < decimals) {
            for(var i = 0; i < (decimals - digits); i++) {
                fraction += '0';
            }
        }
        return num.toString() + '.' + fraction.toString();
}
SmileDeveloper
  • 366
  • 3
  • 10
0

You can play split the number and then take only 4 from the digits after point.

const n = 0.6725505101642719;

const [a, b] = n.toString().split(".");

const res = +`${a}.${b.slice(0,4)}`;

console.log(res)


const modifyDecimal = (number, decimalCount) => {
  const [a, b] = number.toString().split('.');
  return +`${a}.${b.slice(0,decimalCount)}`;
}


console.log(modifyDecimal(0.6725505101642719, 4))
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
0

Hope this will do it for you.

    var num = 0.6720505101642719;
    var inFourDecimal = num.toString().match(/^-?\d+(?:\.\d{0,4})?/)[0];
Thilina Koggalage
  • 1,044
  • 8
  • 16
0
let num = 0.6720505101642719;
(Math.trunc(num*10000)/10000).toFixed(4)
Addis
  • 2,480
  • 2
  • 13
  • 21
  • Please describe in your answer, what was the problem, and how will this snippet solve it, to help others understand this answer – FZs Nov 08 '19 at 21:27