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.)
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