简体   繁体   中英

how to assign json.stringify() to javascript variable

Here in this code, i want to achieve to calculate the sum of particular data that i took from excel file by this line :

  " sumofKoli += JSON.stringify(row.values[4]);". 

My problem is that even this line of code :

 console.log(JSON.stringify(row.values[3])+" Sold number of :"+ JSON.stringify(row.values[4])); 

Gives what i want like "47" which i exactly want as an integer, when i try to sum all the data i am having a result which is like "94559129995555.5.2556149.9". It adds it as a string value, i want it to sum as integer. Can you help me ?

Here is the full code :

 Reader.prototype.readExcel = function(chartType,callback){ // read from a file var workbook = new Excel.Workbook(); var sumofKoli=0; var sumPrice =0; workbook.xlsx.readFile(filename) .then(function(err,results) { var worksheet = workbook.getWorksheet('Sayfa1'); worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) { console.log("----------"); console.log(JSON.stringify(row.values[3])+" Sold number of :"+ JSON.stringify(row.values[4])); console.log("----------"); sumofKoli += JSON.stringify(row.values[4]); console.log(JSON.stringify(row.values[3])+" Sold in price of :"+ JSON.stringify(row.values[5])); sumPrice += JSON.stringify(row.values[5]); console.log("----------"); }); results = { sumofKoli : sumofKoli, sumTutar : sumPrice}; if (err){callback(err,null);} callback(null,results); }); 

You have to use parseInt to convert the string to Number

sumofKoli += parseInt(JSON.stringify(row.values[4])) ;

Convert your json'd values to integers with the parseInt (or parseFloat if you have decimals) functions when trying to sum them.

As your values are currently considered strings, it currently concatenate them instead of adding them.

If your data is only integer, then use parseInt instead of JSON.stringify while adding. In case you have float values too, use parseFloat . Syntax is simple:

sumofKoli += parseInt(row.values[index])

OP is asking to sum integers, so similar to Vladu Ionut's answer it should be:

sumofKoli += parseInt(JSON.stringify(row.values[4]));

But, why are you stringigying a JSON and then parsing it? Why not use the value directly?

sumofKoli += parseInt(row.values[4]);

It seems odd to stringify something just to cast it afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM