1

I am initializing a jquery ui slider that has for example a value of .01, a min of .01, and a max of 5000. My issue is that the max is stopping at 4999.990000000001. Can you see what I am doing wrong?

$( "#sliderModal" ).slider({
    value:r.min_price/100,
    min: r.min_price/100,
    max: r.max_price/100,
    step:0.01,
    slide: function( event, ui ) {
       $( "#amountModal" ).val(ui.value );
    }
});
Gary Storey
  • 1,779
  • 2
  • 14
  • 19
CaitlinHavener
  • 1,408
  • 3
  • 24
  • 53
  • 1
    Try console logging `r.max_price/100` and see what you get. Anyway, you've fallen vitcim to [**floating point arithmetic**](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – adeneo Jan 08 '15 at 22:47
  • 1
    As adeneo said, if you use divide or multiplicate float values, you can get some strange results. Use Math.floor() or Math.round() to get the next value. – Tyr Jan 08 '15 at 22:49

2 Answers2

1

It's a rounding error related to the float values. The easiest way to fix it would to use integers instead:

$( "#sliderModal" ).slider({
    value:r.min_price,
    min: r.min_price,
    max: r.max_price,
    step:1,
    slide: function( event, ui ) {
        $( "#amountModal" ).val(ui.value*100);
    }
});

Notice that I've removed all the /100 operations and multiplied the value by 100.

This assumes that the value is not being displayed as a number - if it is, you're going to get the number multiplied by 100 instead of the nice, neat two-decimal-place number you're looking for.

Kryten
  • 15,230
  • 6
  • 45
  • 68
  • I tried this but I'm getting whole integer values on the slider :( – CaitlinHavener Jan 08 '15 at 22:53
  • Sorry, my mistake - you can change that last line to `$( "#amountModal" ).val(ui.value )` and it should work. It's been a while since I dealt with a slider :-) – Kryten Jan 08 '15 at 22:57
1

A quick fix - floating numbers

in jquery-ui.js and _calculateNewMax function, change the

Math.floor(..

to

Math.round(..

So, if there is

aboveMin = Math.floor((+(max-min).toFixed(this._precision()))/step)*step;

to

aboveMin = Math.round((+(max-min).toFixed(this._precision()))/step)*step;

Note*: you need to edit and link the modded js file localy.

Note**: Check the link to point on jquery-ui.js and not jquery-ui.min.js

checked on v1.11.4

Hope it helps,

giannisepp

giannis.epp
  • 1,489
  • 1
  • 11
  • 9