Keep the Change, You Filthy Animal

Kevin Neyer
2 min readJan 1, 2021

--

One Way of Using the toFixed Method

Photo by Josh Appel on Unsplash

Getting Started

I’ve mentioned in some of my previous articles that I have been working and practicing on a transaction app — a simple application where a user can view and add recent transactions. One practical user story I wanted to implement was being able to see the total of all the transactions. I knew the code to make this happen, so off I went. I put everything in my text editor, saved, and then viewed my app. It was working! Hooray! But, my celebration wasn’t what it should be. This is what I was getting.

Old, Meh Total

While this is mathematically correct, it’s not formatted in the way we view dollars and cents. Now, how to make it the oh, so glorious, 118.50?

The Good Stuff

After a brief Google stint, I found my answer: the toFixed() method! As stated in the MDN docs, the toFixed()method formats a number using a fixed point notation. This is perfectly applied when working with money.

The method takes an optional parameter, which is the number of digits desired after the decimal. But, in this case, since I want change accurately represented(two decimals), the parameter is pretty important!

Examples of Different Parameters.

Perfect! I updated my code to include the toFixed()method, and it looked great.

Updated Code
New, Glorious Total

The nice thing about the toFixed()method is even if the number contains no decimals, it will put zeros(as many your parameter dictates). Again, perfect for monetary values.

toFixed Example

Summing Up

The toFixed()method is perfect for times when a consistent numerical value is desired — perfect for dealing with monetary values. This way, you can accurately keep the change.

--

--