]> source.dussan.org Git - jquery-ui.git/commitdiff
Spinner: Fixed precision when stepping.
authorScott González <scott.gonzalez@gmail.com>
Sat, 13 Aug 2011 03:11:35 +0000 (23:11 -0400)
committerScott González <scott.gonzalez@gmail.com>
Sat, 13 Aug 2011 03:11:35 +0000 (23:11 -0400)
Thanks hughlomas

tests/unit/spinner/spinner_core.js
ui/jquery.ui.spinner.js

index 55b806a7ffb4fb63cac1dfb00a53e4ee8dea73f7..1c2b7ae17959d514288fc99d81555b603f16bd8c 100644 (file)
@@ -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 );
index fa8b065fbbd703700fab694f12066091dbc34058..ffcead73d4117a4d54e2550398b3ddd2eea362f4 100644 (file)
@@ -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;