-
-
Save codenamejason/fd14b90bd2e411be5a8cc43eeeab3228 to your computer and use it in GitHub Desktop.
Used to display formatted money via Knockout binding
This file contains hidden or 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
(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 | |
}; | |
})(); |
This file contains hidden or 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
<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