Dmitry S Dmitry S -4 years ago 84
Javascript Question

different precisions for numeric text depending on number value

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.

Answer Source

precision is a function, but when you're calling it you've missed the parentheses

formattedValue = value.toFixed(precision());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download