2

I am reading an excel file that has decimal, string, and Unicode characters when the user uploads it. I am seeing a floating point error when reading some decimal values(not all). For example, if a number is 0.15 then it is read as 0.150000000002. I need to compare data from the same excel file which is read and stored in DB to the data read from excel to find the difference in both. I am using xlxs-js and also tried using exceljs but was not able to resolve the issue.

   reader.onload = (e: any) => {
     /* read workbook */
     const bstr: any = e.target.result;
     const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'buffer'});

     /* grab first sheet */
     const wsname: string = wb.SheetNames[1];
     const ws: XLSX.WorkSheet = wb.Sheets[wsname];

     /* save data */
     this.data = (XLSX.utils.sheet_to_json(ws, {header: 1}));
     console.log(this.data)
   };
   reader.readAsArrayBuffer(target.files[0]);```

1 Answer 1

1

Javascript has some issues with floating point numbers.

For example:

0.1 + 0.2
=> 0.30000000000000004

If your floating point numbers all have the same amount of decimal places, I would recommend just removing these floating point digits.

parseFloat((0.1 + 0.2).toFixed(2))
=> 0.3

This is not very elegant and does not work if you have different amounts of decimal places.

I would need more information about how your this.data object looks to give you a code snippet to refactor your this.data object / array.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.