0

I have the following string:

const NumberAsString = "75,65";

And I need to parse it as float like this:

Amount: parseFloat(NumberAsString);

I've seen some post that suggested to replace the comma with a dot which works well when the comma is used as thousand separator. But in this case the comma is used as decimal separator If I replace it I get this number: 7.565,00 which is not my number 75.65. Is there any way to parse this number to float without changing it's value?

PD: In my system I have a helper that takes the numbers with the dot as thousand separator and the comma as decimal separator. I cannot avoid this.

pedrodotnet
  • 788
  • 3
  • 16
  • 34
  • 1
    I don't follow where the `7.565,00` number came from in the question. –  Dec 09 '19 at 18:13
  • As I said if I do that the number will change, In my system the dot is used for thousands and the comma for decimals – pedrodotnet Dec 09 '19 at 18:13
  • Is `.` used as a thousands separator? How do you get `7.565,00`? – adiga Dec 09 '19 at 18:13
  • I will edit the post, In my system I have a function helper to convert the . as thousand separator and the comma as decimals separator and I cannot avoid that conversion – pedrodotnet Dec 09 '19 at 18:14

1 Answers1

0

Here is a clunky way of doing it. Using an array and reduce

const tests = ['70,65', '7,000,01', '700'];

const parseNumber = (num) => {
  if(num === undefined) return undefined;
  if(num.indexOf(',') < 0) return parseFloat(num);
  const numArr = num.split(',');
  return parseFloat( numArr.reduce((a, v, i) => a + ((i === numArr.length - 1) ? `.${v}` : v), '') ); 
};

tests.forEach(t => console.log(parseNumber(t)));
Bibberty
  • 4,670
  • 2
  • 8
  • 23