# Formatting Currency

## Motivation

I had previously been using various Google products to monitor my finances. Over the years, these products get slower and slower due to larger and larger amounts of data being graphed.

I decided to look into using Jekyll (offline) to manage the information instead.

One of the first issues that came up was money formatting. I had assumed it would be built in. Indeed, there is a jekyll-money plugin that could be used, if you only care about whole dollars.

I ended up finding this plugin which worked really well at adding the commas.

I wanted to take it a step further. Since I was only using it in an offline project, I didn’t bother making a gem out of it or anything - which is good for us here, because it means we can keep the number of required files pretty minimal for the explanation.

## Making the Plugin

When making plugins for yourself, they go into the _plugins/ directory. If that directory doesn’t exist, create it.

Create the _plugins/money.rb file:

A couple things to note here.

First, I am using sprintf to convert the number to only use 2 decimal places for the cents. This is so that 123.4 would should up as 123.40 and 123.4567 would show up as 123.45. You know, like proper fiat currency.

Second, I am adding css classes to both the positive and negative currencies. I could have used some css child relationships, but didn’t want to risk something like ‘negative’ colliding with any other css plugin.

I am also allowing the caller to specify the html tag. I’m defaulting to div, but in my testing, there was one case where I wanted it to be span instead.

## Styling the Plugin

I’m using Hydejack, which uses a _sass/my-style.scss file. If you don’t have it, create it.

We are right aligning all money, making positive money dark green and negative money red, using accounting style parens.

Like this:

 123.4 123.40 123.45 123.45 -123 (123.00) -0.001 (0.00)

## Using the Plugin

Assuming you have some variable:

Then you can get the behavior above by doing:

If you would rather have a span instead of a div, you can do:

This can be useful if you want to add a footnote, for example:

123.451