Created
December 4, 2018 14:13
-
-
Save luluco250/d7c2ef7aa6316476d78d06cf95be7fb0 to your computer and use it in GitHub Desktop.
Function for formatting decimal numbers, including specifying decimal places and optionally applying localization.
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 for formatting decimal numbers, | |
including specifying decimal places and | |
optionally applying localization. | |
Parameters: | |
n: (Number | String) | |
Number to be formatted. | |
decimals: (Number) | |
Maximum number of decimal places. | |
forceDecimals: (Boolean, optional) | |
Pad number with zeros to meet the | |
requested number of decimal places. | |
locale: (String | Boolean, optional) | |
If a string, it specifies a | |
locale to apply to the result. | |
If 'true', use the default system locale. | |
If undefined or false, no localization | |
will be performed on the result. | |
*/ | |
function formatDecimals(n, decimals, forceDecimals, locale) { | |
if (forceDecimals === undefined) | |
forceDecimals = false; | |
if (typeof n !== "number") | |
n = parseFloat(n); | |
// If NaN | |
if (n !== n) | |
n = 0; | |
if (locale !== undefined && locale !== false) { | |
locale = locale === true ? undefined : locale; | |
if (forceDecimals) | |
return n.toLocaleString(locale, { | |
minimumFractionDigits: decimals, | |
maximumFractionDigits: decimals | |
}); | |
else | |
return n.toLocaleString(locale, { | |
minimumFractionDigits: decimals | |
}); | |
} else { | |
const r = n.toFixed(decimals); | |
return forceDecimals ? r : parseFloat(r).toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment