Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FagnerMartinsBrack/e7c07a64aa2538cc137b405a94cc71e5 to your computer and use it in GitHub Desktop.
Save FagnerMartinsBrack/e7c07a64aa2538cc137b405a94cc71e5 to your computer and use it in GitHub Desktop.
(Medium) - How To Build A Money Data Type In JavaScript
const toDecimalPoint = (cents) => {
const sign = cents < 0 ? '-' : '';
const columns = cents < 0
? cents.toString().split('').slice(1, Infinity)
: cents.toString().split('');
const result = columns.slice();
const dotLocation = columns.length - 2;
if (dotLocation < 0) {
return sign + '$0.0' + result.join('');
}
if (dotLocation === 0) {
return sign + '$0.' + result.join('');
}
if (dotLocation > 0) {
result.splice(dotLocation, 0, '.');
return sign + '$' + result.join('');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment