2021年4月3日星期六

Parse string to floating point number

I'm struggling trying to parse some string that I'm reading from a txt file. When I parse it using parseFloat() it doesn't work as expected, for example when I log a "45.64" parsed to float it shows: 45.63999938964844. This is my code:

  const linesProd = productosTxt.split(/\r?\n/);    var productosObject = { "Productos": [] };    linesProd.forEach(line => {      const fields = line.split("|");            if (fields[0]){        console.log(fields[0])        console.log(typeof(fields[5]))        var fieldsObject = {          productId: fields[0],          id: fields[1],          name: fields[2],          cost: Number.parseFloat(fields[3]),          price1: Number.parseFloat(fields[4]),          price2: Number.parseFloat(fields[5]),        };                productosObject = { ...productosObject, "Productos": [...productosObject.Productos, fieldsObject] };      }    });  

Those fields (cost, price1, price2) are suposed to save those fields from my txt file in number format. The lines in the txt file look something like this:

A1|1|name1|50.5|70|80    A2|2|name2|25.25|35.6|90.15  

I already took a look at some posts here but can't find a proper answer

Any help would be appreciated, Thanks

https://stackoverflow.com/questions/66937185/parse-string-to-floating-point-number April 04, 2021 at 09:07AM

没有评论:

发表评论