McKeene
McKeene

Reputation: 285

Set to 2 decimals for integer in jQuery

I am trying to calculate a total price depending on a users input, but I am experiencing the floating point syndrome. I have checked several other answers, but cannot make it work on my own code. What am I doing wrong?

$(document).ready(function (e) {
    $("select").change(function () {
        var adultTicketsSubtotal = 0;
        var adultPrice = $("#price-adult").data("price");
        $("#ticket-select-adult").each(function () {
            adultTicketsSubtotal = adultPrice * parseInt($(this).val()).toFixed(2);
        })
        $("#adult-total .total").html(adultTicketsSubtotal);
    });
});

Upvotes: 0

Views: 58

Answers (4)

grec0o
grec0o

Reputation: 100

Try this:

adultTicketsSubtotal = adultPrice.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});

Upvotes: 0

raina77ow
raina77ow

Reputation: 106483

Here's one possible approach:

$(function() {
  var $subtotalView = $("#adult-total .total");
  var adultPrice = parseFloat( $("#price-adult").data("price") );
  // TODO: handle NaN case somehow: what if server sets this incorrectly?

  $('#ticket-select-adult').change(function() {
    var ticketsCount = parseInt( this.value, 10 );
    var subtotal = isNaN(ticketsCount) ? 
      ' n/a ' : 
      (ticketsCount * adultPrice).toFixed(2);
    $subtotalView.text(subtotal);
  });
});

Several minor changes here: the DOM traversals are minimized, this.value replaces $(this).val() etc. What's important is type fixation: adultPrice is always a float, ticketsCount always an int (or NaN for placeholder values, but this case is handled), and subtotal is always a string of the given format.

Upvotes: 3

Amar Singh
Amar Singh

Reputation: 5622

In place of parseInt , Use parseFloat . Do multiplication and then use toFixed

parseInt changes the number to an integer.

adultTicketsSubtotal = (adultPrice * (parseFloat($(this).val()))).toFixed(2);

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

You need to use the .toFixed() method like:

$("#adult-total .total").html(adultTicketsSubtotal.toFixed(2));

Upvotes: 1

Related Questions