Skip to content

Instantly share code, notes, and snippets.

@codenamejason
Forked from jakiestfu/ko-money.js
Last active July 26, 2017 19:25
Show Gist options
  • Save codenamejason/fd14b90bd2e411be5a8cc43eeeab3228 to your computer and use it in GitHub Desktop.
Save codenamejason/fd14b90bd2e411be5a8cc43eeeab3228 to your computer and use it in GitHub Desktop.
Used to display formatted money via Knockout binding
(function(){
var toMoney = function(num){
if(num === null || num === undefined){
return 0;
}
// Use this if your number is a string:
// return '$' + (Number(num).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') );
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';
}
if(valueUnwrapped === null || valueUnwrapped === undefined){
return 0;
}
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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment