Reputation: 33
I use knockout to show numeric value as following:
<td class="right"><span data-bind="numericTextWithoutNumericSeparator: Volume, precision: 4"></span></td>
In js file I have this:
ko.bindingHandlers.numericTextWithoutNumericSeparator = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
precision = ko.utils.unwrapObservable(allBindingsAccessor().precision) || ko.bindingHandlers.numericText.defaultPrecision,
formattedValue = value.toFixed(precision);
ko.bindingHandlers.text.update(element, function () { return formattedValue; });
},
defaultPrecision: 2
};
But I need to show numbers with 2 decimal digits if last 2 of 4 decimal digits are zero, otheriwse show numbers with 4 decimals.
Here is example:
1.1234 -> 1.1234
1.1200 -> 1.12
1.1350 -> 1.1350
1.0000 -> 1.00
How should I chande my js file to achieve this?
EDIT: I edited my js file to this:
ko.bindingHandlers.numericTextWithoutNumericSeparator = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
precision = function () {
if (value % Math.round(value, 2) == 0) {
return 2;
} else {
return 4;
}
},
formattedValue = value.toFixed(precision);
ko.bindingHandlers.text.update(element, function () { return formattedValue; });
}
};
But get rounding numbers up to 0 digits.
Upvotes: 1
Views: 36
Reputation: 136104
precision
is a function, but when you're calling it you've missed the parentheses
formattedValue = value.toFixed(precision());
Upvotes: 1
Reputation: 1548
You could try something like this:
function shortNumber(number, precision) {
var short = number.toFixed(precision)
short = short + new Array(precision - short.split('.')[1].length + 1).join(0)
return (short == number ? short : number)
}
Upvotes: 0