Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Pen by Rahul P Nath.
Enter a value and tab off and you will see the currency $ coming in automatically.
<p>Enter bid price: <input data-bind="value: formattedPrice"/></p>
function MyViewModel() {
this.price = ko.observable(25.99);
this.formattedPrice = ko.computed({
// Similar to Convert function on IValueConverter
read: function () {
return '$' + this.price().toFixed(2);
// Similar to ConvertBack on IValueConverter
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, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
owner: this
ko.applyBindings(new MyViewModel());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment