I have a requirement of formating the decimal value to US dollar format (that is every decimal number should be appended with a $ symbol at the beginning & introduce comma after every 3 digits.
For example : 999999999 should be converted to $999,999,999.00 for display purpose while the original value should be retained as it is for further calculations.
self.MonthlyAppliedEmployerContributionAmount = ko.observable(MonthlyAppliedEmployerContribution);
self.MonthlyAppliedEmployerContributionAmountFormatted = ko.computed({
read: function () {
return '$' + parseFloat(self.MonthlyAppliedEmployerContributionAmount()).toFixed(2);
},
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^\.\d]/g, ""));
self.MonthlyAppliedEmployerContributionAmount(isNaN(value) ? 0 : value); // Write to underlying storage
}
});
Here while reading the observable property, I am appending $ at the beginning & .toFixed(2) helped me to achieve to restrict 2 decimals.
But I m not sure how to introduce comma after every three digits.
NB : In the KO write method I am removing all the formatting that is introduced in the read meothod.
I dont want to use Jquery mask plugin as most of them are not directly from Jquery lib, but made by some third party, which might break at some point of time.
Appreciate an early response.
You can use this regular expression to insert thousand separators:
function addThousandSeparator(s) {
return s.replace(/(\d)(?:(?=\d+(?=[^\d.]))(?=(?:\d{3})+\b)|(?=\d+(?=\.))(?=(?:\d{3})+(?=\.)))/gm, '$1,');
}
If you need another thousand separator, replace the comma in '$1,'
with your separator.
So you would have:
read: function () {
return '$' + addThousandSeparator(parseFloat(self.MonthlyAppliedEmployerContributionAmount())
.toFixed(2));
}