How to limit the number of decimals in javascript?

Asked

Viewed 331 times

0

I have a function to change quantity in the shopping cart and I need to limit the number of decimals, because if I add more than 2 units the value is like this: 89.69999999999

Example: https://codepen.io/bombcat/pen/4e482b3f6f96e7c90213f7c887738c1b

Html:

    <div class="quantity" id="product1">
  <input style="font-size:21px;" type="button" value="-" onclick='javascript:     document.getElementById("number").value--;' class="operator">
  <input id="number" type="number" value="1" class="qty" name="picpac" disabled>
   <input style="font-size:21px;" type="button" value="+"  onclick='javascript:     document.getElementById("number").value++;'  class="operator">
</div>

<input type="hidden" id="product1_base_price" value="29.90">

<div id="product1_total_price">
  29.90
</div>

javascript

$(document).ready(function() {

  $(".operator").on('click',function() {
      $("#product1_total_price").text($("#product1_base_price").val() * $("#number").val());
  });
});

1 answer

3


Flash,

One option is to use toFixed javascript, see an example with your code:

$(document).ready(function() {
  $(".operator").on('click',function() {
    let total = $("#product1_base_price").val() * $("#number").val();

    $("#product1_total_price").text(total.toFixed(2));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="quantity" id="product1">
  <input style="font-size:21px;" type="button" value="-" onclick='javascript:     document.getElementById("number").value--;' class="operator">
  <input id="number" type="number" value="1" class="qty" name="picpac" disabled>
  <input style="font-size:21px;" type="button" value="+"  onclick='javascript:     document.getElementById("number").value++;'  class="operator">
</div>

<input type="hidden" id="product1_base_price" value="29.90">

<div id="product1_total_price">
  29.90
</div>

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.