修复Javascript中的小数点(使用范围滑块)

时间:2018-01-04 11:03:38

标签: javascript



    var slider = document.getElementById("pSliderRange");
    var output = document.getElementById("SliderPrice");
    var slots = document.getElementById("NumberOfSlots");
    slots.innerHTML = slider.value; // Display the default slider value
    output.innerHTML = slider.value / 1.5;

    // Update the current slider value (each time you drag the slider handle)
    slider.oninput = function() {
      slots.innerHTML = this.value;
      output.innerHTML = this.value / 1.5;
    }

<input type="range" min="3" max="60" value="2" class="p-slider" id="pSliderRange">
<p class="normal-text">Total Slots : <span id="NumberOfSlots"></span></p>
            <p class="normal-text">Monthly Price : $<span class="normal-text" id="SliderPrice"></span></p>
&#13;
&#13;
&#13;

您好, 我用Range Slider制作了一个价格柜台。 根据老虎机计算价格。它简单地将插槽数量除以1.5 我面临的唯一问题是小数点。有没有办法限制小数点?我搜索了许多论坛,但没有得到答案(也许),因为我使用滑块计算值。 任何帮助将非常感谢:) 谢谢.. :))

3 个答案:

答案 0 :(得分:0)

您可以使用toPresicionhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision

toFixedhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

的示例:

var value = 1.234;
console.log(value.toFixed(2)); // result: '1.23'
console.log(value.toPrecision(3)); // result: '1.23'

答案 1 :(得分:0)

您可以使用toFixed(x)来保持x个小数位数

&#13;
&#13;
var slider = document.getElementById("pSliderRange");
    var output = document.getElementById("SliderPrice");
    var slots = document.getElementById("NumberOfSlots");
    slots.innerHTML = slider.value; // Display the default slider value
    output.innerHTML = slider.value / 1.5;

    // Update the current slider value (each time you drag the slider handle)
    slider.oninput = function() {
      slots.innerHTML = this.value;
      output.innerHTML = (this.value / 1.5).toFixed(2);
    }
&#13;
<input type="range" min="3" max="60" value="2" class="p-slider" id="pSliderRange">
<p class="normal-text">Total Slots : <span id="NumberOfSlots"></span></p>
            <p class="normal-text">Monthly Price : $<span class="normal-text" id="SliderPrice"></span></p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

output.innerHTML = (this.value / 1.5).toFixed(2);

这可以解决您的问题。