Reputation: 93
I am attempting to bind together a javascript function, but I keep getting problems with the decimal numeric values being converted automatically (53.000 is converted to 53000) when binding. Below is the example of what I am attempting to achieve;
<script data-bind="text: 'getNewValue(Price ',' + VAT + ');'"></script>
Where VAT is 53.000 and Price is 378.
I have tried appending .toFixed(2) without success like so;
<script data-bind="text: 'getNewValue(Price.toFixed(2) ',' + VAT.toFixed(2) + ');'"></script>
Thanks in advance for any help with this!
/Peter
Upvotes: 1
Views: 93
Reputation: 2665
I wrote this originally to handle phone numbers but it seems to work well for currency. (Note: I am using USD here). With this subscribable computed, you just append it to any currency element and it will display correctly as a currency, but you retain the value as a float/int. This makes it easier to use it in calculations throughout the view model.
function ToAmount() {
return ko.computed({
read: function() {
var num = parseFloat(ko.unwrap(this));
return this() ? "$" + num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",") : "$0.00";
},
write: function(_amount) {
this(_amount);
this.notifySubscribers();
},
owner: this,
}).extend({
notify: 'always'
});
}
ko.subscribable.fn.ToAmount = ToAmount;
function vm() {
var self = this;
self.Money = ko.observable(12.345);
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input data-bind="value: Money.ToAmount()">
Upvotes: 3
Reputation: 111
In knockout.js you can define the function directly in the data-bind like this:
<script data-bind="text: getNewValue(Price.toFixed(2) + ',' + VAT.toFixed(2));"></script>
This would call your getNewValue function with both values decimal fixed to 2 in one variable
If you just want a concatenation of those 2 values, you can also do it directly in the databind like this:
<script data-bind="text: Price.toFixed(2) + ', ' + VAT.toFixed(2);"></script>
This would result in: 53.00, 378.00
Upvotes: 1