43

How will i round margin_total to 3 decimal places?

margin_total = margin_total + parseFloat(marginObj.value);
document.getElementById('margin_total').value = margin_total;
Sanju Menon
  • 625
  • 1
  • 6
  • 16

4 Answers4

76

Use num.toFixed(d) to convert a number into the String representation of that number in base 10 with d digits after the decimal point, in this case,

margin_total.toFixed(3);
Paul S.
  • 64,864
  • 9
  • 122
  • 138
14

const roundedDown = Math.round(6.426475 * 1000) / 1000
console.log(roundedDown) // 6.426

const roundedUp = Math.round(6.426575 * 1000) / 1000
console.log(roundedUp) // 6.427

The above code rounds to 3 decimal places (dp)

To round to 2 dp use 100 instead of 1000 (all occurrences)

To round to 4 dp use 10000 instead of 1000

You get the idea!

Or use this function:

const round = (n, dp) => {
  const h = +('1'.padEnd(dp + 1, '0')) // 10 or 100 or 1000 or etc
  return Math.round(n * h) / h
}

console.log('round(2.3454, 3)', round(2.3454, 3)) // 2.345
console.log('round(2.3456, 3)', round(2.3456, 3)) // 2.346
console.log('round(2.3456, 2)', round(2.3456, 2)) // 2.35

Or just use Lodash round which has the same signature - for example, _.round(2.3456, 2)

danday74
  • 52,471
  • 49
  • 232
  • 283
10

The toFixed() method converts a number into a string, keeping a specified number of decimals. A string representation of input that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

function myFunction() {
  var num = 5.56789;
  var n = num.toFixed(3)
  document.getElementById("demo").innerHTML = n;
}
<p>Click the button to display the fixed number.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
Rayon
  • 36,219
  • 4
  • 49
  • 76
5
const num = 70.012345678900
console.log(parseFloat(num.toFixed(3)));
// expected output: 70.012
Nditah
  • 1,429
  • 19
  • 23