Created
April 7, 2021 14:35
-
-
Save OliverJAsh/8eb1d4eb3ed455f86cc8756be499ba8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
Number.isNaN(reversedVal)?0:+reversedVal
always returns+reversedVal
because callingNumber.isNaN
on a string is always false.Number.isNaN(+reversedVal)?0:+reversedVal
(note+
inside theisNaN
call) could be used to return 0 if the string does not appear to be a number.