Bill Shihara
Bill Shihara

Reputation: 375

How do I bind a number and prevent scientific notation?

I would like to bind a number to an input box and make sure that it is never displayed in scientific notation.

<input type="text" class="form-control text-right" 
       data-bind="value: myData, valueUpdate: 'afterkeydown'" />

The input box should accept a decimal number of up to 8 places and I should be able to modify myData from my viewModel and have it shown as a number such as .00000001. I'd like myData to be a number because I perform arithmetic on it within the viewModel.

The example numeric extender doesn't work for me because if you start trying to type .00001, it starts to update the value from underneath the user. I've tried using ratelimiting, but that setting is finicky as it eventually changes the value from under the user as well.

Is there a way to code an extender such that the display binding to the input box is always toFixed(8) while some underlying data is always numeric? The opposite would be okay where the underlying data is text but can be accessed somehow as numeric when needed.

Thank you

Upvotes: 1

Views: 313

Answers (2)

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

To separate the value in your viewmodel from the value displayed, you can use a computed observable.

For example, you can have a viewmodel like this:

function ViewModel() {
    var self = this;
    this.myValue = ko.observable(0);
    this.displayedValue = ko.computed({
        read: return self.myValue().toFixed(8),
        write: function (value) { 
            self.myValue(value); //maybe do something to ensure you save a number
        } 
    });
}

When you need to do a calculation, use myValue, but use displayedValue for your html:

<input type="text" class="form-control text-right" 
       data-bind="value: displayedValue, valueUpdate: 'afterkeydown'" />

Upvotes: 1

The Dark
The Dark

Reputation: 8514

The reason the value is being updated from underneath the user is because you are using valueUpdate: 'afterkeydown'. This will be a problem for anything that will change the text, as it will confuse the user if the text changes as they type. If you don't use valueUpdate: 'afterkeydown' then the text can be changed when they tab out of the field. The extenders work fine for that case.

Upvotes: 0

Related Questions