Search code examples
javascriptjquerynumbersnumber-formattingtrailing

How to round and format a number in JavaScript without trailing zeros?


I have two inputs that get multiplied and I need the result to be rounded down without trailing zeros. I have tried a few different built-in methods, such as number.toFixed(2), but they did not produce the desired result.

This issue can be reproduced by typing the numbers 20 and 6 into the first and second inputs here:

$(document).on("change", ".p-cell, .s-cell", () => {
    var val1 = $(".p-cell").val();
    var val2 = $(".s-cell").val();    
    var total = val1 / 100 * val2;
    
    $(".w-cell").val(total).trigger("input");
});
<input class="p-cell" type="text" value="0" />
<input class="s-cell" type="text" value="0" />
<input class="w-cell" type="text" value="0" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Solution

  • You could use Number.prototype.toFixed(), .toFixed(2) if you want to show two decimals:

    const $pCell = $(".p-cell");
    const $sCell = $(".s-cell");
    const $wCell = $(".w-cell");
    
    $(document).on('input', '.p-cel, .s-cell', () => {
      const val1 = $pCell.val() || 0;
      const val2 = $sCell.val() || 0;
      const total = (val1 / 100 * val2).toFixed(2);
        
      $wCell.val(total);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input class="p-cell" type="text" value="0" />
    <input class="s-cell" type="text" value="0" />
    <input class="w-cell" type="text" value="0" readonly />

    Additionally, if you want to remove any number of trailing zeroes, so 1.20 becomes 1.2 and 2.00 becomes 2, you could use String.prototype.replace() with a RegExp: total.replace(/\.?0+$/, ''):

    const $pCell = $(".p-cell");
    const $sCell = $(".s-cell");
    const $wCell = $(".w-cell");
    
    $(document).on('input', '.p-cel, .s-cell', () => {
      const val1 = $pCell.val() || 0;
      const val2 = $sCell.val() || 0;
      const total = (val1 / 100 * val2).toFixed(2);
        
      $wCell.val(total.replace(/\.?0+$/, ''));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input class="p-cell" type="text" value="0" />
    <input class="s-cell" type="text" value="0" />
    <input class="w-cell" type="text" value="0" readonly />