I'm trying to round the output of some calculations to 3 or less decimal places, so they can stored compactly in a comma-delimited text file. That is 2 should be stored as 2 not 2.000, 3.14 should be stored as 3.14 not 3.140, and so on.
The problem is, 0.001*Math.round(1000*value)
works sometimes, but not all the time. When I check the file that was saved, it contains output like this:
0.165,1,1,0.17300000000000001,0,0,0.3,0.16,0.184,0.20800000000000002
, which defeats the purpose of rounding for compactness in a text file.
You are encountering this error because 0.001 in binary have not an exact value but an approx value that is 0.0000001100011.. so due to this approximation you are not getting value in 3 or less decimals in some cases
so to fix that you can use division instead of multiplication instead of *0.001 use /1000
mathematically both are same, but due to how JavaScript internally handles floating-point arithmetic, division can sometimes result in a more "exact" value than multiplication when it comes to binary representation.
So try using
Math.round(1000*value)/1000