Reputation: 9247
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?
Upvotes: 5
Views: 147
Reputation: 20361
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));
Upvotes: 0
Reputation: 3266
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
.
Upvotes: 0
Reputation: 16184
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
Upvotes: -1
Reputation: 827
You can use:
parseFloat('10.000.000,00'.replace(/\./g, '').replace(',', '.'), 10)
Upvotes: 0