简体   繁体   中英

D3 parse number from string

I am new to using D3.js and I am having problems converting string data into a number. I am using a CSV with one column called "Belgium" composed by numbers like these ones: 54,345 or 1,234,567.

I tried to convert them into numbers by using

data.forEach(function(d) {
    d.Belgium = +d.Belgium; 
}

but I get NaN as a result. I also tried using

d.Belgium = parseInt(d.Belgium);

but it takes the figures before the first comma and removes the rest of the number. For example, if one number is 1,234,562, using parseInt() I just get 1. If the figure is 982,381, it remains 982.

Remove all , with string.replace(searchvalue, newvalue) :

parseInt(str.replace(/,/g, ""))

so for example:

 console.log(parseInt("1,234,562".replace(/,/g, ""))) 

As noted below, use parseFloat instead of parseInt if your numbers may contain decimals eg 3.141,592 to keep the floating point number.

I took a bit of a different approach. I used .split(",") to split the value into an array at every , , then used .join("") to join each index of the array with empty spaces. Used the + operator for ease of use but could have been parseFloat() as well.

 let stringNumber = "1,250,234.093"; let numStringNumber = +stringNumber.split(",").join(""); console.log(numStringNumber); console.log(typeof numStringNumber); 

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