<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
First Script:
(Math.trunc(1005)/1000).toFixed(3)
Math.trunc(1005)
simply truncates the number 1005, which remains 1005.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, like1004.9999999999999
.Math.trunc(1004.9999999999999)
then truncates this to1004
.1.004
.toFixed(3)
correctly formats this as"1.004"
.