Skip to content

Commit 257021b

Browse files
committed
Spinner: Fixed precision when stepping.
Thanks hughlomas
1 parent 6c1bf56 commit 257021b

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

tests/unit/spinner/spinner_core.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,4 +185,21 @@ test( "focus text field when pressing button", function() {
185185
ok( element[ 0 ] === document.activeElement, "focused after" );
186186
});
187187

188+
test( "precision", function() {
189+
expect( 2 );
190+
var element = $( "#spin" ).spinner({
191+
value: .05,
192+
step: .0001
193+
});
194+
element.spinner( "stepUp" );
195+
equal( element.val(), "0.0501", "precision from step" );
196+
197+
element.spinner( "option", {
198+
value: 1.05,
199+
step: 1
200+
});
201+
element.spinner( "stepDown" );
202+
equal( element.val(), "0.05", "precision from value" );
203+
});
204+
188205
})( jQuery );

ui/jquery.ui.spinner.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,13 @@ $.widget( "ui.spinner", {
228228
this.counter = 1;
229229
}
230230

231-
var newVal = this.value() + step * this._increment( this.counter );
231+
var newVal = this.value() + step * this._increment( this.counter ),
232+
// fix precision from bad JS floating point math
233+
precision = Math.max( this._precision( this.value() ),
234+
this._precision( this.options.step ) );
232235

233236
// clamp the new value
234-
newVal = this._trimValue( newVal );
237+
newVal = this._trimValue( newVal.toFixed( precision ) );
235238

236239
if ( !this.spinning || this._trigger( "spin", event, { value: newVal } ) !== false) {
237240
this._value( newVal );
@@ -245,6 +248,12 @@ $.widget( "ui.spinner", {
245248
1;
246249
},
247250

251+
_precision: function( num ) {
252+
var str = num.toString(),
253+
decimal = str.indexOf( "." );
254+
return decimal === -1 ? 0 : str.length - decimal - 1;
255+
},
256+
248257
_trimValue: function( value ) {
249258
var options = this.options;
250259

0 commit comments

Comments
 (0)