Testing some rounding logic in js
Regular expression testing with qunit
by ozzymcduff
HTML
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
function roundTo(newValue, precision){
var roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
return valueToWrite;
}
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
valueToWrite = roundTo(newValue, precision);
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
test("rounding values", function () {
equal(roundTo(10.11,2), 10.11, "basic case");
equal(roundTo(10.1111,2), 10.11, "more dec");
equal(roundTo(10.1,2), 10.1, "less dec");
});
test("rounding string values", function () {
equal(roundTo('10.11',2), 10.11, "basic case");
equal(roundTo('10.1111',2), 10.11, "more dec");
equal(roundTo('10.1',2), 10.1, "less dec");
});
test("rounding values <1", function () {
equal(roundTo(0.11,2), 0.11, "basic case");
equal(roundTo(0.1111,2), 0.11, "more dec");
equal(roundTo(0.1,2), 0.1, "less dec");
});
test("rounding string values <1", function () {
equal(roundTo('0.11',2), 0.11, "basic case");
...