I'm getting unexpected float values when I read in my file. So I have a program that accumulates scores for elements in my object e.g. [{a:0.001}, {b:0.002},....]
. The scores are incremented by 0.001. When I exit out, the array is written to a file with the following function:
function(filename, result, msg)
{
var fs = require('fs');
var stream = fs.createWriteStream(filename);
stream.once('open', function(fd)
{
stream.write(JSON.stringify(result));
stream.end(function()
{
console.log(msg);
});
});
}
and when I start the program, in another module, the object is read in as so:
fs.readFile('scoreboard.json', 'utf8', function (err, data)
{
console.log(JSON.parse(data));
}
When I initially run my script, it produces the expected results - scores that are multiples of 0.001. But when I save and reload the object, the scores turn up as:
[{a:0.009000000000000001},{b:0.011000000000000003}]
Is this occurring because of the way fs is reading and writing floats? To fix this should I explicitly convert the scores to floats after loading and convert them back into strings before writing?