Skip to content

Instantly share code, notes, and snippets.

@lucabertolasi
Last active March 4, 2018 20:48
Show Gist options
  • Save lucabertolasi/09b85f85d915e494f6596327c72c9506 to your computer and use it in GitHub Desktop.
Save lucabertolasi/09b85f85d915e494f6596327c72c9506 to your computer and use it in GitHub Desktop.
[JavaScript] Format currency: from cents<number> to <string> or viceversa (e.g. 120030040 --> "1.200.300,40" --> 120030040).
/**
* @license
* Copyright (c) 2017-present, Luca Bertolasi. All Rights Reserved.
*
* This software is licensed under the terms of the MIT license,
* a copy of which can be found at https://opensource.org/licenses/MIT
*/
function formatCurrency(amount, strToNum) {
// default behaviour:
// input 'amount' should be expressed in cents: 120030040
// output will be in european format: 1.200.300,40
// 'strToNum' (bool) behaviour:
// input 'amount' should be expressed in european format: 1.200.300,40
// output will be in cents: 120030040
// input validation
const MATCH_NON_DIGITS_REGEXP = /[^\d]/gi
let amountStr
if (typeof amount === 'number' && !isNaN(amount)) {
amountStr = Math.abs(amount).toString().replace(MATCH_NON_DIGITS_REGEXP, '')
} else if (typeof amount === 'string') {
let _amount = amount.replace(MATCH_NON_DIGITS_REGEXP, '')
// no need to 'Math.abs(...)' here becase the live above stripped any non-digit characters, including minus sign
// 'parseInt(...)' will remove leading zeroes
amountStr = _amount.length === 0 ? '0' : parseInt(_amount).toString()
} else {
amountStr = '0'
}
if (strToNum) { return parseInt(amountStr) }
// not enought digits
if (amountStr.length === 1) { amountStr = `00${amountStr}`; }
if (amountStr.length === 2) { amountStr = `0${amountStr}`; }
// at this point there are at least 3 digits
let amountArr = amountStr.split('');
// set local vars
let cents = '';
let ones = '';
let tens = '';
let hundreds = '';
let thousands = '';
let thousandsCount = 0;
let formattedAmount = '';
// cents
cents = amountArr.pop();
cents = `${amountArr.pop()}${cents}`;
// ones
ones = amountArr.pop();
// minimum digits amount
formattedAmount = `${ones},${cents}`;
// extra digit: tens
if (amountArr.length > 0) {
tens = amountArr.pop();
formattedAmount = `${tens}${formattedAmount}`;
// extra digit: hundreds
if (amountArr.length > 0) {
hundreds = amountArr.pop();
formattedAmount = `${hundreds}${formattedAmount}`;
// extra digits: thousands
while (amountArr.length > 0) {
// group thousands triplets and add separator
thousands = '';
thousandsCount = 0;
do {
thousands = `${amountArr.pop()}${thousands}`;
thousandsCount += 1;
} while (amountArr.length > 0 && thousandsCount < 3);
formattedAmount = `${thousands}.${formattedAmount}`;
} // thousands
} // hundreds
} // tens
return formattedAmount;
} // formatCurrency
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment