0

I've seen there are quite a few questions about decimal precision and display in Javascript. the thing is that I came to a solution that I thought it was gonna be enough for me'

The key thing is that I'm trying to parse to a string to round and then back to numbers using expressions like this.

return parseFloat(num.toFixed(2));

But there are some cases that it doesn't work as expected. To be honest I'm not sure if it has to do with the way I'm using ko or the javascript code for parsing I put in place. But let's say that in the below fiddle you type 14.385 in the upper text box, both fields will be properly rounded and will display the correct number of decimals, but without deleting the number you add 3333 (that means 14.393333) and the upper one won't be rounded. That's just an example because there are some strange behaviours.

Yo can see the fiddle here http://jsfiddle.net/RTexF/

Thanks

Edit. I add the code as per judgeja indication (I didn't understand the reason to ask for a code when you link fiddle, I see the point now)

The script

var decimalValue = 0.25;

function ViewModel() {
    var self = this;

    self.submittedValue = ko.observable(decimalValue);

    self.percentage = ko.computed({
        read: function() {
            alert('read');
            if (isNaN(parseFloat(self.submittedValue())))
                return '';

            var num = self.submittedValue() * 100;
            return parseFloat(num.toFixed(2));

        },
        write: function(value) {
            alert('write');
            value = isNaN(value) ? '' : parseFloat((value / 100).toFixed(4));
            self.submittedValue(value);
        },
        owner: self
    });
}

ko.applyBindings(new ViewModel());

And the html

<p><input data-bind="value:percentage"></input></p>
<p><input data-bind="value:submittedValue"></input></p>

EDIT:

Know that it's an old one but I wanted to note that adding this to the write method

self.percentage.notifySubscribers(value);

it fixes the issue (ideally we could check against the current value and just notifiy if it actually changes)

Fiddle : http://jsfiddle.net/RTexF/1/ and http://jsfiddle.net/RTexF/2/

4

1 回答 1

0

alert("read")如果您在read:write:alert("write")中放入 an ,然后再次运行您的示例,可能会帮助您考虑这一点。

当您第一次更改顶框时,底框通过写入写入,然后顶框随着可观察值的变化而重新计算submittedValue,您将看到读取百分比被命中。

下次您编辑顶部框时,写入将再次被击中,因为我们正在更改值,这是有道理的,但由于submittedValue未更改,因此读取不会再次发生,因为它所依赖的 observable 不会已经改变。

于 2013-07-18T09:50:42.527 回答