diff options
author | Scott González <scott.gonzalez@gmail.com> | 2011-08-12 23:11:35 -0400 |
---|---|---|
committer | Scott González <scott.gonzalez@gmail.com> | 2011-08-12 23:11:35 -0400 |
commit | 257021b1af4f5414fb71ada695d86bd51bb5dc04 (patch) | |
tree | 62425f102f3599ad54ea9b22a27c0eb7a7340863 | |
parent | 6c1bf56029ab2ebe45a8a5e29de1a6d9b42c8f89 (diff) | |
download | jquery-ui-257021b1af4f5414fb71ada695d86bd51bb5dc04.tar.gz jquery-ui-257021b1af4f5414fb71ada695d86bd51bb5dc04.zip |
Spinner: Fixed precision when stepping.
Thanks hughlomas
-rw-r--r-- | tests/unit/spinner/spinner_core.js | 17 | ||||
-rw-r--r-- | ui/jquery.ui.spinner.js | 13 |
2 files changed, 28 insertions, 2 deletions
diff --git a/tests/unit/spinner/spinner_core.js b/tests/unit/spinner/spinner_core.js index 55b806a7f..1c2b7ae17 100644 --- a/tests/unit/spinner/spinner_core.js +++ b/tests/unit/spinner/spinner_core.js @@ -185,4 +185,21 @@ test( "focus text field when pressing button", function() { ok( element[ 0 ] === document.activeElement, "focused after" ); }); +test( "precision", function() { + expect( 2 ); + var element = $( "#spin" ).spinner({ + value: .05, + step: .0001 + }); + element.spinner( "stepUp" ); + equal( element.val(), "0.0501", "precision from step" ); + + element.spinner( "option", { + value: 1.05, + step: 1 + }); + element.spinner( "stepDown" ); + equal( element.val(), "0.05", "precision from value" ); +}); + })( jQuery ); diff --git a/ui/jquery.ui.spinner.js b/ui/jquery.ui.spinner.js index fa8b065fb..ffcead73d 100644 --- a/ui/jquery.ui.spinner.js +++ b/ui/jquery.ui.spinner.js @@ -228,10 +228,13 @@ $.widget( "ui.spinner", { this.counter = 1; } - var newVal = this.value() + step * this._increment( this.counter ); + var newVal = this.value() + step * this._increment( this.counter ), + // fix precision from bad JS floating point math + precision = Math.max( this._precision( this.value() ), + this._precision( this.options.step ) ); // clamp the new value - newVal = this._trimValue( newVal ); + newVal = this._trimValue( newVal.toFixed( precision ) ); if ( !this.spinning || this._trigger( "spin", event, { value: newVal } ) !== false) { this._value( newVal ); @@ -245,6 +248,12 @@ $.widget( "ui.spinner", { 1; }, + _precision: function( num ) { + var str = num.toString(), + decimal = str.indexOf( "." ); + return decimal === -1 ? 0 : str.length - decimal - 1; + }, + _trimValue: function( value ) { var options = this.options; |