将字符串转换为数字,在js中保留逗号



是否有任何方法将字符串(如"7,1")转换为数字并在转换后保留逗号?我尝试过parseInt,但它会忽略第一个值之后的所有内容。还有别的办法吗?

当你将它们转换为数字时,你不能保留逗号,但是你可以在JS数组上使用.join()方法。你可以这样做。

var str = '7,1'
// Convert to numbers
// This will return [7, 1]
var nums = str.split(',').map((num) => Number(num))
// Reverse to previous values, but it will be converted to String type
var revertedStr = nums.join(',')
var str = '7,1';
// Split the above string variable into array
var numList = str.split(',');
// Type cast all these string values into number value
// Now we have an array of with each element in number format 
numList = str.split(',').map((num) => Number(num));
console.log(numList);
// Now as per your requirement if you jion them with comma then it will again become string.
console.log(typeof (numList.join(',')));
// So technically it's not possible to have comma as a value in number variable.
// If you can tell a bit about your use case then we might be able to help you with some alternative.```

最新更新