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.

4
  • 1
    I don't follow where the 7.565,00 number came from in the question. Commented Dec 9, 2019 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 Commented Dec 9, 2019 at 18:13
  • Is . used as a thousands separator? How do you get 7.565,00? Commented Dec 9, 2019 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 Commented Dec 9, 2019 at 18:14

1 Answer 1

-1

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)));

Sign up to request clarification or add additional context in comments.

1 Comment

it failed in some test cases: // Test cases const toFloat = "1.234.567,90"; const toFloat2 = "1,234,567.90"; const toFloat3 = "1234567,90"; const toFloat4 = "1234567.90"; const toFloat5 = "1234567.9"; const toFloat6 = "1234567";

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.