user16358489
user16358489

Reputation:

Having trouble with implementing toFixed() for two decimals behind to comma

This is my code

function computeTotal() {
 var total = 0;
  $('.price-selected-option').each(function() {
    total += parseFloat($(this).text().replace(',', '.'));
  })
  $('.total-price').text(total)
}

I tried adding .toFixed(2) this way:

function computeTotal() {
 var total = 0;
  $('.price-selected-option').each(function() {
    total += parseFloat($(this).text().replace(',', '.').toFixed(2));
  })
  $('.total-price').text(total)
}

But I (partly) understand this does not work because of .text in the same line. I’m very new to Javascript so any help is highly appreciated.

So to be clear I always want 2 decimals te be displayed behind the comma. Also when for example te price is €8.5, then it should be €8.50 or when it’s €8 it should be €8,00

I looked into How to parse float with two decimal places in javascript? but couldn’t find an answer because of my code being different i.e. includes .text

Upvotes: 0

Views: 1122

Answers (2)

nook
nook

Reputation: 1884

It's because toFixed() is a Number method and not a String method.

parseFloat returns a number, but toFixed returns a string. so you need to parseFloat again after that.

function computeTotal() {
  var total = 0;
  $('.price-selected-option').each(function() {
    // value is a number
    const value = parseFloat($(this).text().replace(',', '.'))
    total += value
  })
  $('.total-price').text(total.toFixed(2));
}

Upvotes: 1

rmiguelrivero
rmiguelrivero

Reputation: 966

I would recommend you to learn about Intl.NumberFormat. Please check the docs here. It has plenty of useful options as the second parameter to fine-tune it to your needs.

var numbers = [8, 4312.1, 3.14159, 0.0014, 0.00643];
var results = numbers.map((number) => [ 
  number,
  new Intl.NumberFormat('en', { maximumFractionDigits: 2, style: 'currency', currency: 'EUR' }).format(number)
]);

results.forEach(([input, output]) => {
  console.log(`${input} => ${output}`);
});

Upvotes: 0

Related Questions