0

I am beginner in JS and this code

$('.brutto_amount').each(function (index, value) {
    let amount = $(this).text().replace(' brutto / rok', '').replace('(', ''); console.log(amount);
    if (discountType == 0) {
        let newAmount = (amount - discountValue).toFixed(2);
        if(newAmount < 0) newAmount = 1;
        $(this).html(`${newAmount} brutto / rok `);
    } else if (discountType == 1) {
        let newAmount = (amount - ((parseInt(amount) * parseInt(discountValue)) / 100)).toFixed(2);
        if(newAmount < 0) newAmount = 1;
        $(this).html(`${newAmount} brutto / rok `);
    }
});

works fine so far.

How can I subtract 23% VAT from the variable newAmount and round it to 2 decimal places?

Joe - GMapsBook.com
  • 15,787
  • 4
  • 23
  • 68
trzew
  • 385
  • 1
  • 4
  • 13
  • 2
    The first is a simple math problem, if your `newAmount` value is a brutto value, calculating the netto, with a vat of 23%, is as simple as `newAmount / 123 * 100`. Use `calculatedNetto.toFixed(2)` to round that to 2 numbers. Be aware though, that calculations in JS will have rounding errors due to floating point precision. For further information about the issue and how to circumvent that, read [this](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Lapskaus Aug 14 '20 at 13:42

1 Answers1

0

I solved the problem similar to what Lapskaus mentions in the comments:

The first is a simple math problem, if your newAmount value is a brutto value, calculating the netto, with a vat of 23%, is as simple as newAmount / 123 * 100. Use calculatedNetto.toFixed(2) to round that to 2 numbers. Be aware though, that calculations in JS will have rounding errors due to floating point precision. For further information about the issue and how to circumvent that, read this. newAmount will be a brutto value which will be 123% from which you want to calculate the 100% value. You substract 23% off of 123 which is too much

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Jan
  • 36
  • 2
  • newAmount will be a brutto value which will be 123% from which you want to calculate the 100% value. You substract 23% off of 123 which is too much – Lapskaus Aug 14 '20 at 13:48