Convert a string into a number keeping the commas in js

762 views Asked by At

is there any way to convert a string like "7,1" into a number and keep the commas after the conversion?. I've tried parseInt but that will ignore everything after the first value. Is there another way around it?

2

There are 2 answers

0
Kaung Myat Lwin On

You can't keep commas when you convert them to numbers, however you can use .join() method on JS Arrays. Here is how you can do it.

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(',')
0
Shubham Jha On
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.```