Skip to content

Instantly share code, notes, and snippets.

@Ambratolm
Last active February 23, 2022 19:09
Show Gist options
  • Save Ambratolm/dd5604a8a6285ebd9c33e0d7c70edfd6 to your computer and use it in GitHub Desktop.
Save Ambratolm/dd5604a8a6285ebd9c33e0d7c70edfd6 to your computer and use it in GitHub Desktop.
Convert a formatted money string value (that may contain currencies, decimals, brackets ...etc) to a raw numeric value (to use it in calculations).
function moneyRawValue(value = 0, decimalSeparator = ",") {
if (typeof value === "number") return value;
const rawValue = parseFloat(
value
.replace(/\((?=\d+)(.*)\)/, "-$1")
.replace(new RegExp(`[^0-9-${decimalSeparator}]`, "g"), "")
.replace(decimalSeparator, ".")
);
return isNaN(rawValue) ? 0 : rawValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment