Skip to content

Instantly share code, notes, and snippets.

@christopher-talke
Last active June 19, 2019 01:04
Show Gist options
  • Save christopher-talke/4db3486de14e3c31d1ebd0226c496671 to your computer and use it in GitHub Desktop.
Save christopher-talke/4db3486de14e3c31d1ebd0226c496671 to your computer and use it in GitHub Desktop.
Custom Gist to Handle Money Formats.
const handleMoney = {
// Converts a number format (NOT FLOAT) to a human readble money value that is typically associated to a float.
// @param value = number
// @output result = float
toHuman: function(value) {
const options = {
minimumFractionDigits: 2
};
const formatter = new Intl.NumberFormat('en-AU', options);
return formatter.format(value / 100);
},
// Converts a float format to a computer readble value that can be used to accuratly calculate values.
// @param value = float
// @output result = number
toComputer: function(value) {
if (typeof value === 'string') {
value = parseFloat(value.replace(/,/gi, ''));
}
return value * 100;
}
};
// Example 1 - Function Calls
const { toHuman, toComputer } = handleMoney;
const purchaseAmount = 500000; // $50.00
const HUMAN_READABLE = toHuman(purchaseAmount);
const COMPUTER_READABLE = toComputer(HUMAN_READABLE);
// Example 1 - Outputs
console.log('\nOriginal Value: ', purchaseAmount);
console.log('Human Value: ', `$${HUMAN_READABLE}`);
console.log('Computer Value: ', COMPUTER_READABLE);
// Original Value: 500000
// Human Value: $5,000.00
// Computer Value: 500000
// Example 2 - Function Calls
const cart = [1009, 2750, 350, -1000];
const TOTAL_COMPUTED_READABLE = cart.reduce((acc, item) => (acc += item), 0);
const TOTAL_HUMAN_READABLE = toHuman(TOTAL_COMPUTED_READABLE);
const BACK_TO_COMPUTED = toComputer(TOTAL_HUMAN_READABLE);
// Example 2 - Outputs
console.log('\nTotal Computed Value: ', TOTAL_COMPUTED_READABLE);
console.log('Total Human Value: ', `$${TOTAL_HUMAN_READABLE}`);
console.log('Back To Computed: ', BACK_TO_COMPUTED);
// Total Computed Value: 3109
// Total Human Value: $31.09
// Back To Computed: 3109
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment