-1

I have an issue with the decimals in a result in my script, it gives unlimited decimals, I want to limit it to 2, I have tried using to.fixed(2) without luck, but the script broke.

This is my script:

    $.each(rows, function () {
    quantity = $(this).find('[data-quantity]').val();
    if (quantity == '') {
        quantity = 1;
        $(this).find('[data-quantity]').val(1);
    }
    _amount = parseFloat($(this).find('td.rate input').val()) * quantity;

    $(this).find('td.amount').html(_amount);
    subtotal += _amount;
    row = $(this);
    item_taxes = $(this).find('select.tax').selectpicker('val');
    if (item_taxes) {
        $.each(item_taxes, function (i, taxname) {
            taxrate = row.find('select.tax [value="' + taxname + '"]').data('taxrate');
            calculated_tax = (_amount / 100 * taxrate);


            if (!taxes.hasOwnProperty(taxname)) {
                if (taxrate != 0) {
                    _tax_name = taxname.split('|');
                    tax_row = '<tr class="tax-area"><td>' + _tax_name[0] + '(' + taxrate + '%)</td><td id="tax_id_' + slugify(taxname) + '"></td></tr>';
                    $(discount_area).after(tax_row);
                    taxes[taxname] = calculated_tax;
                }
            } else {
                // Increment total from this tax
                taxes[taxname] = taxes[taxname] += calculated_tax;
            }
        });
    }
});

The code line that does the operation is:

calculated_tax = (_amount / 100 * taxrate);
karel
  • 5,489
  • 46
  • 45
  • 50
  • is `.toFixed(2)` not `to.fixed(2)` – Titus Nov 19 '19 at 18:18
  • 1
    Does this answer your question? [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – Samarth Saxena Nov 19 '19 at 18:20

2 Answers2

1

The correct is toFixed(), not to.fixed(), see the example:

let number = 12.128361;
let _amount = number.toFixed(2);
let calculated_tax = (_amount / 100 * 100);
console.log(calculated_tax);
leofalmeida
  • 323
  • 1
  • 10
0

Use this method to round to any amount of decimal places:

let v = 3.486894716724;
let rounded = Math.round(v * 100) / 100; // => 3.49

Multiply and divide by 10 to round to one DP, 100 for 2DP, 1000 for 3, etc...

Sebi S
  • 63
  • 7