Working with Dollars and Cents in JavaScript: The Definitive Guide

Why hello there dear internet friend!

Welcome to my blog and the “definitive guide” on working with dollars and cents in JavaScript ๐Ÿ˜‰ So the title of this post is a bit misleading, all you really need is one nifty method to format your numbers as dollars and cents:

yourNumberVariable.toFixed(2)

That’s it! Pretty nifty right?

I currently happen to be working on a personal finance app called Moolabeast at the moment, so that’s why I decided to publish this post. After releasing the latest version of the app I noticed a bug that was causing some of my financial transactions to format something like $ 34.089999999999996 , yikes! Thus the interest in this topic.

Previously I was using some one-liner of JavaScript I found on StackOverflow for formatting my dollar amounts. The line of code I was using had some wonky regular expression in it that I did not understand or care to investigate further until things went awry in my app. However, after digging into how this little code snippet worked, I discovered that the only part that really mattered was the toFixed method. I had assumed that this regular expression was important for… something? However, I was wrong! You really just need toFixed and you are good to go.

If you’d like a reference to play around with, check out my “definitive guide” below:

(UPDATE 11/26/2019: It looks like the regex was for adding commas, whoops! If you need commas, which I assume you do, check the last section of the code sample below for the regex magic.)

(UPDATE: 11/30/2019: The regex magic described above does not work with floating point numbers represented as strings. One could write a regular expression that does work with whole numbers, however, I’m not very good with writing regular expressions. Therefore, I’ve included a little function which I wrote in case anyone needs to add commas to whole numbers.)

console.log("****************************************************");
console.log("**** Working With Dollars & Cents in JavaScript ****");
console.log("**** ~ The Definitive Guide ~ ****");
console.log("****************************************************");
console.log('\n');
const formatAsDollarsAndCents = (value) => {
var newValue = parseFloat(value);
newValue = newValue.toFixed(2);
return newValue;
}
// Floating Point Numbers Formatted to 2 Decimal Places
console.log("Floating Point Numbers Formatted to 2 Decimal Places");
const nonStandardAmountFormatted = formatAsDollarsAndCents(34.089999999999996);
console.log(nonStandardAmountFormatted);
const oneDecimalPlaceFormatted = formatAsDollarsAndCents(1.1);
console.log(oneDecimalPlaceFormatted);
const wholeNumberFormatted = formatAsDollarsAndCents(1);
console.log(wholeNumberFormatted);
console.log('\n');
// Strings Formatted to 2 Decimal Places
console.log("Cast As String...");
const nonStandardAmountFormattedAsString = nonStandardAmountFormatted.toString();
console.log('$' + nonStandardAmountFormattedAsString);
const oneDecimalPlaceFormattedAsString = oneDecimalPlaceFormatted.toString();
console.log('$' + oneDecimalPlaceFormattedAsString);
const wholeNumberFormattedAsString = wholeNumberFormatted.toString();
console.log('$' + wholeNumberFormattedAsString);
console.log('\n');
// Need to add commas? Here's the regex magic sprinkled in...
const myNumber = 1300000.89
const myNumberAsString = myNumber.toString();
const myNumberWithCommas = myNumberAsString.replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.log('Add commas... ');
console.log('$' + myNumberWithCommas);
// Edge case, need to add commas to a whole number? I've written a function that
// will add commas to a string of numeric characters. This is helpful when working
// with integers, as the regular expression above does not work with whole numbers.
// (One could write a regular expression that works with whole numbers, but I'm not
// very good with regex so I just wrote a function and moved on with my life ๐Ÿ˜‰
function getWholeNumberWithCommas(wholeNumberStr) {
// Step One, Reverse String
var reversedString = "";
var indexOfLastChar = wholeNumberStr.length - 1;
for (var i = indexOfLastChar; i >= 0; i--) {
reversedString = reversedString + wholeNumberStr[i];
}
// Step Two, Add Commas Every Third Char
var reversedStringWithCommas = "";
for (var i = 0; i < reversedString.length; i++) {
// every third char, add a comma and the next char
if (i % 3 === 0 && i !== 0) {
reversedStringWithCommas = reversedStringWithCommas + "," + reversedString[i];
} else {
reversedStringWithCommas = reversedStringWithCommas + reversedString[i];
}
}
// Step Three, Reverse reversedStringWithCommas, and we'll have
// the whole number with commas that we want
var wholeNumberWithCommas = "";
indexOfLastChar = reversedStringWithCommas.length - 1;
for (var i = indexOfLastChar; i >= 0; i--) {
wholeNumberWithCommas = wholeNumberWithCommas + reversedStringWithCommas[i];
}
// Step Four, return wholeNumberWithCommas
return wholeNumberWithCommas;
}
console.log('\n');
var testNumber = "9283749823749872398472938742983748";
var testNumberWithCommas = getWholeNumberWithCommas(testNumber);
console.log('Add commas to a whole number (represented as a string)');
console.log(testNumberWithCommas);
console.log('\n');
console.log("****************************************************");
console.log("****************************************************");
console.log("****************************************************");
 

topherPedersen