SheetJS / sheetjs

📗 SheetJS Spreadsheet Data Toolkit -- New home https://git.sheetjs.com/SheetJS/sheetjs
https://sheetjs.com/
Apache License 2.0
35.02k stars 8k forks source link

Decimal numbers, wrong number of decimals #2790

Closed theodortoma96 closed 2 years ago

theodortoma96 commented 2 years ago

Hi,

I have an excel file with decimal numbers (see price column). image

The issue is that some numbers are wrongly parsed, for example 3.4 becomes 3.399999999999999.

This is how I try to read from file:

const readExcelFile = async function (file) {
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.onerror = () => {
      reader.abort()
      reject(new DOMException('Problem parsing input file'))
    }

    reader.onload = function (e) {
      const data = e.target.result

      const workbook = read(data, {
        type: 'binary',
        cellDates: true
      })

      resolve(workbook.SheetNames.map(sheetName => {
        return utils.sheet_to_json(workbook.Sheets[sheetName], { header: 1, range: 0, defval: null, rawNumbers: true, raw: true })
      }))
    }

    reader.readAsBinaryString(file)
  })
}

This is how the values look when after read:

D7: {t: 'n', v: 3.1999999999999997, w: '3.2'} D8: {t: 'n', v: 3.2499999999999996, w: '3.25'} D9: {t: 'n', v: 3.2999999999999994, w: '3.3'} D10: {t: 'n', v: 3.349999999999999, w: '3.35'} D11: {t: 'n', v: 3.399999999999999, w: '3.4'}

Note that I've also tried without rawNumbers and raw options but same result.

SheetJSDev commented 2 years ago

Those are the actual numbers stored in the file. Since Excel and JS both use IEEE754 numbers, you can reproduce the effect in your browser:

console.log(3.5 - 0.1 - 0.2)