Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created April 7, 2021 14:35
Show Gist options
  • Save OliverJAsh/8eb1d4eb3ed455f86cc8756be499ba8e to your computer and use it in GitHub Desktop.
Save OliverJAsh/8eb1d4eb3ed455f86cc8756be499ba8e to your computer and use it in GitHub Desktop.
function reverseFormatNumber(val,locale){
var parts = new Intl.NumberFormat(locale).formatToParts(1111.1);
var group = parts.find(part => part.type === 'group').value;
var decimal = parts.find(part => part.type === 'decimal').value;
var reversedVal = val.replace(new RegExp('\\' + group, 'g'), '');
reversedVal = reversedVal.replace(new RegExp('\\' + decimal, 'g'), '.');
return Number.isNaN(reversedVal)?0:+reversedVal;
}
console.log(reverseFormatNumber('1,234.56','en'));
console.log(reverseFormatNumber('1.234,56','de'));
@BenceSzalai
Copy link

I think Number.isNaN(reversedVal)?0:+reversedVal always returns +reversedVal because calling Number.isNaN on a string is always false. Number.isNaN(+reversedVal)?0:+reversedVal (note + inside the isNaN call) could be used to return 0 if the string does not appear to be a number.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment