Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading excel in javascript is converting long numbers to Exponential

I am reading an excel file using SheetJs, but the issue is it's converting long numbers like 3577888990098 to exponential like 3.52E+12.

This question is not duplicate, because:

File columns can be random and system won't know which ones are numbers and which ones are Strings (Alphabetical) or both.

So how to get rid of this?

Here is my code:

function handleFileSelect(evt) {
    var files = evt.target.files;
    var i, f;
    //Loop through files
    for (i = 0, f = files[i]; i != files.length; ++i) {
        var name = f.name;
        const reader = new FileReader();
        reader.onload = (evt) => {
            /* Parse data */
            const bstr = evt.target.result;
            const wb = XLSX.read(bstr, {type:'binary'});
            /* Get first worksheet */
            const wsname = wb.SheetNames[0];
            const ws = wb.Sheets[wsname];
            /* Convert array of arrays */
            const data = XLSX.utils.sheet_to_csv(ws, {header:1});
            /* Update state */
            console.log("DATA>>>"+data);
        };
        reader.readAsBinaryString(f);
    }
}
like image 579
Noman Ali Avatar asked Oct 23 '25 18:10

Noman Ali


2 Answers

By default sheet_to_csv take the formatted numbers.

To avoid the formatted value and to take raw inputs (original values) you have to add parameter in sheet_to_csv method you have to set rawNumbers to true

Try this code

const data = XLSX.utils.sheet_to_csv(worksheet, { rawNumbers: true });
like image 93
Parth Tagadiya Avatar answered Oct 26 '25 07:10

Parth Tagadiya


How about using toFixed() for only the Number objects

var x = 3577888990098;
var y = '3577888990098';

if(typeof(x) === 'number') {
    x = x.toFixed(); // it will not convert it to exponential.
}
like image 29
rahul_sann Avatar answered Oct 26 '25 07:10

rahul_sann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!