McKeene McKeene - 1 year ago 79
jQuery Question

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);

Answer Source

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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download