Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handlebars currency helper and test
Handlebars.registerHelper('currency', function(amount, options) {
if (typeof(amount) === 'string') { amount = options.contexts[0].get(amount); }
var rounded = Math.round(amount * 100);
var dec = rounded % 100;
var whole = rounded / 100 - dec / 100;
var decStr = '' + dec;
return '$' + whole + '.' + decStr + ( decStr.length < 2 ? '0' : '');
});
test("USD", function () {
//Fails
var t = Handlebars.compile("{{currency 0.1}}");
equal(t(), "$0.10", "Passed in cents");
//Passes
var t = Handlebars.compile("{{currency amount}}");
equal(t({amount: 0.15}), "$0.15", "Passed in key");
});
@AndrewEastwood

This comment has been minimized.

Copy link

@AndrewEastwood AndrewEastwood commented Jul 9, 2014

Here It's better to replace #5 with var whole = Math.round(rounded / 100 - dec / 100);
because I've been able to get the following result: "0.9999999999999999.63"
It's when rounded is 163 and dec is 63
Then JS does crazy stuff with math and the whole will contain 0.9999999999999999
So I think adding Math.round would be better 😀

@mikeweitz

This comment has been minimized.

Copy link

@mikeweitz mikeweitz commented Sep 11, 2015

This function misinterprets cents when passing in an amount with 01 - 09 cents (ex 10.05 will output as "$10.50"). Try:

Handlebars.registerHelper('currency', function(amount, options) {
    var numericAmount = typeof amount === 'string' ? options.contexts[0].get(amount) : amount;
    var pennies = Math.round(numericAmount * 100);
    var cents = pennies % 100;
    var dollars = Math.round(pennies / 100 - cents / 100);
    var centsStr = '' + cents;
    var result = '$' + dollars + '.' + ( centsStr.length < 2 ? '0'+cents : cents);

    return '$' + dollars + '.' + ( centsStr.length < 2 ? '0' + cents : cents);
});
@lazamar

This comment has been minimized.

Copy link

@lazamar lazamar commented May 11, 2016

Once you have the amount you could just use built-in javascript methods to format the currency. Something like:

var num = new Number(amount);
var formattedNumber = num.toLocaleString('en-US', {style: 'currency', currency: 'USD'});

// Example
// amount: 2000.345
// output: $2,000.35 
@swilliams

This comment has been minimized.

Copy link

@swilliams swilliams commented Jul 28, 2016

@lazamar JSHint complains about using the Number constructor (since it's type is object instead of number). toLocaleString is available on primitives though: var x = 100; x.toLocaleString(...);

However it is not supported on all browsers, most notably Safari on iOS; it returns the original value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment