ekbayrak2
ekbayrak2

Reputation: 41

display number 2 decimals

I have this code with 3 sliders that adds up all the 3 values of the sliders and displays it on the page, I want it to display it with 2 decimals after the comma. I tried using .toFixed(2) but I don't know where to place it exactly. Here is my code :

<div class="wrapper2">
  <input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
      <hr />

  <input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
       <hr />
      <input  class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />

       <hr />

 <div  id = "info"></div>

var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");

$('#ram').slider({
    value : 0,
    formatter: function(value) {
        return 'RAM: ' + value + 'GB';
    }
});

$('#diskSpace').slider({
    value : 0,
    formatter: function(value) {
        return 'Disk Space: ' + value + 'GB';
    }
});

$('#cpu').slider({
    value : 0,
    formatter: function(value) {
        return 'CPU : ' + value + ' Cores';
    }
});

// If You want to change input text using slider handler
$('.slider').on('slide', function(slider){

  var ram = $("#ram").val()*3.50;
  var diskSpace = $("#diskSpace").val()*1.20;
  var cpu = $("#cpu").val() * 6.30;
  $("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));

});


// If you want to change slider using input text
$("#inputValue").on("keyup", function() {
    var val = Math.abs(parseInt(this.value, 10) || minSliderValue);
    this.value = val > maxSliderValue ? maxSliderValue : val;
    $('#ram','diskSpace','cpu').slider.toFixed(2)('setValue', val);
});

Jsfiddle: http://jsfiddle.net/4c2m3cup/34/

Upvotes: 0

Views: 232

Answers (2)

Oliver Orchard
Oliver Orchard

Reputation: 592

You were parsing to an int. When you parse to int you lose the decimal places.

$("#info").html(parseInt(ram)+ parseInt(diskSpace)+ parseInt(cpu));

You can add them up and use x.toFixed(2). This will give you two decimal places just change the number as desired.

$("#info").html((ram + diskSpace + cpu).toFixed(2));

Upvotes: 1

Geeky
Geeky

Reputation: 7496

change your summing up code to the following

$('.slider').on('slide', function(slider){

  var ram = $("#ram").val()*3.50;
  var diskSpace = $("#diskSpace").val()*1.20;
  var cpu = $("#cpu").val() * 6.30;
  var totalSum=(parseFloat(ram)+ parseFloat(diskSpace)+ parseFloat(cpu)).toFixed(2);
  $("#info").html(totalSum);

});

Hope it helps

Upvotes: 1

Related Questions