Skip to content

Instantly share code, notes, and snippets.

@cleytonferrari
Created August 9, 2012 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cleytonferrari/3300583 to your computer and use it in GitHub Desktop.
Save cleytonferrari/3300583 to your computer and use it in GitHub Desktop.
Formatar moeda com Knockout JS
//baseado em http://jsfiddle.net/digitalbush/R6MPU/
jQuery(function ($) {
function empenhoViewModel() {
var self = this;
self.valorTotal = ko.observable().dinheiro();
};
var format = function (value) {
if (value === '' || isNaN(value)) value = 0;
toks = Number(value).toFixed(2).replace('-', '').split('.');
var display = 'R$ ' + $.map(toks[0].split('').reverse(), function (elm, i) {
return [(i % 3 === 0 && i > 0 ? '.' : ''), elm];
}).reverse().join('') + ',' + toks[1];
return value < 0 ? '-' + display : display;
};
ko.subscribable.fn.dinheiro = function () {
var target = this;
var writeTarget = function (valor) {
valor = String(valor).replace('.', '').replace(',', '.').replace(/[^0-9.-]/g, '');
target(parseFloat(valor));
};
var result = ko.computed({
read: function () {
return target();
},
write: writeTarget
});
result.formatted = ko.computed({
read: function () {
return format(target());
},
write: writeTarget
});
result.isNegative = ko.computed(function () {
return target() < 0;
});
return result;
};
var viewModel = new empenhoViewModel();
ko.applyBindings(viewModel);
viewModel.init();
});
<!-- imput em razor (ASP.NET MVC) -->
@Html.TextBoxFor(x => x.ValorTotal, new { @data_bind = "value: valorTotal.formatted" })
<!-- imput simples em html -->
<input data-bind="value: valorTotal.formatted" type="text" value="">
<span data-bind="text: valorTotal.formatted"></span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment