Skip to content

Instantly share code, notes, and snippets.

@jakiestfu
Last active February 14, 2018 10:46
Show Gist options
  • Save jakiestfu/7894971 to your computer and use it in GitHub Desktop.
Save jakiestfu/7894971 to your computer and use it in GitHub Desktop.
Used to display formatted money via Knockout binding
(function(){
var toMoney = function(num){
return '$' + (num.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') );
};
var handler = function(element, valueAccessor, allBindings){
var $el = $(element);
var method;
// Gives us the real value if it is a computed observable or not
var valueUnwrapped = ko.unwrap( valueAccessor() );
if($el.is(':input')){
method = 'val';
} else {
method = 'text';
}
return $el[method]( toMoney( valueUnwrapped ) );
};
ko.bindingHandlers.money = {
update: handler
};
})();
<span data-bind="money: 1234567.2"></span> <!-- Outputs $1,234,567.20 -->
<input type="text" data-bind="money: 1234567"> <!-- Sets value to $1,234,567.00 -->
@brianmhunt
Copy link

Another option for the toMoney function, just as an illustration for the curious (in coffeescript):

toMoney = (value) ->
  options =
    currency: 'CAD'
    style: 'currency'
    maximumFractionDigits: 2
  return value.toLocaleString(locale, options)

Cheers

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