Math.Trunc function reducing the value by 0.001

64 Views Asked by At

<div id="demo1"></div>
<div id="demo2"></div>

<script>
document.getElementById("demo1").innerHTML = (Math.trunc(1005)/1000).toFixed(3);
</script>
 
<!-- *The above usage gives the value as* **1.005** -->

<script>
document.getElementById("demo2").innerHTML = (Math.trunc(1.005*1000)/1000).toFixed(3);
</script>

<!-- *The next usage gives the value as* **1.004** -->

<script>
document.getElementById("demo3").innerHTML = (Math.trunc(1.004*1000)/1000).toFixed(3);
</script>

<!-- *The next usage gives the value again as* **1.004** -->

Why is this happening?

Since I am using Math.Trunc(), it should render same values after using toFixed() function but its value is getting reduced.enter image description here

1

There are 1 best solutions below

2
On

First Script: (Math.trunc(1005)/1000).toFixed(3)

  • Math.trunc(1005) simply truncates the number 1005, which remains 1005.
  • Then, you divide 1005 by 1000, resulting in 1.005.
  • toFixed(3) correctly formats this as "1.005".

Second Script: (Math.trunc(1.005*1000)/1000).toFixed(3)

  • 1.005 * 1000 in JavaScript doesn't exactly equal 1005 due to floating-point precision errors. Instead, it results in something slightly less, like 1004.9999999999999.
  • Math.trunc(1004.9999999999999) then truncates this to 1004.
  • Dividing 1004 by 1000 gives 1.004.
  • toFixed(3) correctly formats this as "1.004".