Truncated JS does not take 0 to the right

0

How can I truncate a decimal number with zeros to the right, since it always truncates to the natural number, that is, if there is a 0 it does not take it?

function myRound(num, dec) {
  var exp = Math.pow(10, dec || 2); // 2 decimales por defecto
  return parseInt(num * exp, 10) / exp;
}

var num = 2.70;
console.log('Con 1 decimales:', myRound(num, 1));
console.log('Con 2 decimales:', myRound(num));
console.log('Con 3 decimales:', myRound(num, 3));
<html>
<head>

</head>
<body>
</body>

</html>
    
asked by Ivxn 16.05.2018 в 19:08
source

1 answer

2

If you want extra zeros to the right, you can not force JS to show float 2.7 as 2.70 unless you cast it as String. For that, the primitive Number offers the toFixed method (which returns strings).

function myRound(num, dec) {
  if(dec===undefined) {
     dec=2;  // 2 decimales por defecto
  }
  var exp = Math.pow(10, dec);
  return Number(parseInt(num * exp, 10) / exp).toFixed(dec);
}

var num = 2.70;
console.log('Con 1 decimales:', myRound(num, 1));
console.log('Con 2 decimales:', myRound(num));
console.log('Con 3 decimales:', myRound(num, 3));
    
answered by 16.05.2018 / 19:44
source