1

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?

willd
  • 119
  • 1
  • 6
  • 1
    You can't keep commas, because numbers don't contain commas. Repace comma (the first-one in the string) with the dot, then you can use parseFloat to create a number. – Teemu Apr 05 '23 at 04:10
  • 1
    Numbers in JavaScript are visually represented with dot as decimal. When you output them (as strings) you can make use of [Number.toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) to do the needed formatting for your locale. To parse strings with comma as decimal separator to Numbers, check https://stackoverflow.com/questions/7431833/convert-string-with-dot-or-comma-as-decimal-separator-to-number-in-javascript – James Apr 05 '23 at 04:13
  • A comma in a number is not a valid number, it should be a string. – anand Apr 05 '23 at 06:20
  • @willd This requirement is not clear to me. I did not see any difference before and after the conversion as end result will always be a string. – Debug Diva Apr 07 '23 at 07:22

2 Answers2

0

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(',')
Kaung Myat Lwin
  • 1,049
  • 1
  • 9
  • 23
0
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.```