Created
March 21, 2013 17:54
-
-
Save kayleg/5215127 to your computer and use it in GitHub Desktop.
Handlebars currency helper and test
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
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"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lazamar JSHint complains about using the
Number
constructor (since it's type isobject
instead ofnumber
).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.