skip to Main Content

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

Answers


  1. 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(',')
    
    Login or Signup to reply.
  2. 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.```
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search