5

How can I convert this string to get 1000000? The problem is I always get 10000:

console.log(parseFloat('10.000.000,00'.replace('.', ',').replace(/,(?=[^,]*$)/, '.')),'test');

Any suggestions?

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
None
  • 8,817
  • 26
  • 96
  • 171

5 Answers5

4
parseFloat(a.replace(/\./g, '').replace(',', '.'))
f278f1b2
  • 301
  • 1
  • 7
0

You can use:

parseFloat('10.000.000,00'.replace(/\./g, '').replace(',', '.'), 10)
Anshu Kumar
  • 807
  • 1
  • 8
  • 27
0

You can also do:
'10.000.000,00'.split(',')[0].replace(/\./g,'');

So, in this case, you can use it for any decimal value after the , so if you wish later to add this value, you can get it with [1] location returned by split.

Yuvals
  • 3,094
  • 5
  • 32
  • 60
0

You could try this:

/** German number format info */
const numberFomatInfoDeDe = {
  decimalSeparator: ",",
  numberGroupSeparator: ".",
};

/**
 * Converts a string to a number.
 * @param str The string to convert.
 * @param numberFomatInfo Information for the conversion.
 * @returns The number. NaN if the string cannot be converted.
 */
function stringToNumber(str, numberFomatInfo) {
  let tmp = str;

  tmp = tmp.replace(new RegExp("\\" + numberFomatInfo.numberGroupSeparator, "g"), "");
  tmp = tmp.replace(numberFomatInfo.decimalSeparator, ".");

  return parseFloat(tmp);
}

// Tests
console.log(stringToNumber("10.000.000,00", numberFomatInfoDeDe));
console.log(stringToNumber("10,00", numberFomatInfoDeDe));
console.log(stringToNumber("-10", numberFomatInfoDeDe));
console.log(stringToNumber("asdf", numberFomatInfoDeDe));
Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
-1

your code probably isn't doing what you seem to be expecting it to do. you should try running each sub-expression separately in a debugger, i.e:

'10.000.000,00'.replace('.', ',')

gives back "10,000.000,00", i.e. just the first period is replaced by a comma, while:

"10,000.000,00".replace(/,(?=[^,]*$)/, '.')

evaluates to: "10,000.000.00", i.e. the last comma is replaced by a period. you then do:

parseFloat("10,000.000.00")

which evaluates to 10.

note that you can also pass a function to the replace function which can be used as:

'10.000.000,00'.replace(/[.,]/g, m => ({'.':'', ',':'.'}[m]))

which makes a single pass over the string, removing periods and replacing commas with periods

Sam Mason
  • 15,216
  • 1
  • 41
  • 60