Disable rounding in jQuery knob library

162 Views Asked by At

I have a float value, that comes from JSON data. Calling console.log() displays the correct value fe: 12.3. But I don't know why, when I try to set this value with val() it rounds the value fe: 12.0?

If the value is 23.4, displays 23.0. If 31.8, displays 32.0.

This is the snippet in which I want to set the value:

$(document).ready(function() {
  var color = 'green'
  $('.dial').knob({
    'min': 0,
    'max': 100,
    'width': "100%",
    'height': "100%",
    'displayInput': true,
    'fgColor': color,
    'readOnly': true,
    'draw': function() {
      $(this.i)
        .val(this.cv.toFixed(1) + 'ms')
        .css('font-size', '15pt')
        .css('color', 'black');
    }
  });
});

And this is the code that sets the value:

$.ajax({
  url: "stats.php",
  type: "POST",
  data: data
}).done(function(answer) {
  console.log(answer)
  time = answer.TIME
  time = parseFloat(time)
  $(<?php echo "host".$i ?>).val(time);
  $(<?php echo "host".$i ?>).trigger('change');
  setColor();
});

Thank you!

1

There are 1 best solutions below

0
On BEST ANSWER

By default jQuery Knob only supports integers. To make it correctly format floating point values, you need to set the step parameter to the level of accuracy you require. In this case, 0.1:

$(document).ready(function() {
  var color = 'green'

  $('.dial').knob({
    min: 0.0,
    max: 100.0,
    step: 0.1, // add this
    width: "100%",
    height: "100%",
    displayInput: true,
    fgColor: color,
    readOnly: true,
    draw: function() {
      $(this.i).val(this.cv.toFixed(1) + 'ms').css({
        'font-size': '1em',
        'color': 'black'
      });
    }
  });

  // for testing
  let value = 12.3;
  $('.dial').val(value).trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Knob/1.2.13/jquery.knob.min.js" integrity="sha512-NhRZzPdzMOMf005Xmd4JonwPftz4Pe99mRVcFeRDcdCtfjv46zPIi/7ZKScbpHD/V0HB1Eb+ZWigMqw94VUVaw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<input type="text" class="dial" />

Also note that I adjusted the font size of the output so that it fits within the control.