2

Does anyone know how to make a number from a string with comma separators, in JS. I got: "23,21" and I want to get it as a number value.

"23,21" --> 23,21

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • 2
    That's not possible. A number has a dot as decimal separator. You can convert `"23,21"` --> `23.21` or `"23.21"` --> `23.21`. – jabaa Sep 22 '21 at 09:59
  • Does this answer your question? [Javascript parse float is ignoring the decimals after my comma](https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma) – Donald Duck Jun 10 '22 at 10:17

3 Answers3

0

You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

But before you need to replace comma for dot.

parseFloat('23,21'.replace(/,/, '.')); // == 23.21

let x = '16,5';
parseFloat(x.replace(/,/, '.')); // == 16.5
Po1nt
  • 522
  • 1
  • 4
  • 13
0

You can but not with the "comma" (,). In some countries people do use commas instead of dots to write decimals. If that's the case then what you can do is:

let a = "23,25";
let b = a.replaceAll(',', '.');
console.log(parseFloat(b));

But doing the this with the comma is also not wrong. But you will only get the part before the decimal.

i.e. 23 in your case

0

Check if you want this.

var str = '23,21';
console.log((str.split(",").map((i) => Number(i))));

UPDATE

 var str = '23,21';
 var arr = str.split(",").map((i) => Number(i));
 console.log(parseFloat(arr.join('.')));
Fc0001
  • 58
  • 12