Search code examples
javascriptrangeslider

Rangeslider odd output value on only one number


I have something of an 'odd' issue that I'm struggling to resolve.

I'm using RangesliderJS (https://rangeslider.js.org) and for the most part it's all working fine. However, I need the output and the actual field value to be slightly different (due to the way something else is calculated, but it's largely irrelevant here I think). The slider shows percentages - from zero to ten. The value needs to be 0.01 for 1%, 0.1 for 10% etc.

However, for the user I need to show the 'real' number - i.e 1%, 5% etc.

This is how I've done that;

$(document).ready(function() {
    $('input[type="range"]').rangeslider({
polyfill : false,
onInit : function() {
    this.output = $( '<div class="range-output" />' ).insertAfter( this.$range ).html( this.$element.val() * 100 );
},
onSlide : function( position, value ) {
    this.output.html( value * 100 );
    console.log(this.value);
}
});
});

Which works fine. However, I have an odd scenario where what should be output as 7% actually shows as 7.000000000000001% - every other number shows as it should, and the console logs the value correctly at 0.07 too.

This is purely for UI purposes, so I'm happy to 'hack' a fix if there is one, but I'm keen to understand why it's doing this too (JS is not my forte!)


Solution

  • While I'm still none-the-wiser as to the cause, I have resolved the issue by using Math.round ;

          $('input[type="range"]').rangeslider({
    polyfill : false,
    onInit : function() {
        this.output = $( '<div class="range-output" />' ).insertAfter( this.$range ).html( this.$element.val() * 100 );
    },
    onSlide : function( position, value ) {
        this.output.html(Math.round( value * 100 ));
        console.log(this.value);
    }
    });
    });