Param-Ganak
Param-Ganak

Reputation: 5875

Problem with mathematical calculation in jQuery

I have two text boxes. I enter number in one textbox. I write following jQuery for that textbox which get executed when the focus out from first text box. The jQuery code takes the entered value from first text box and multiply it by a decimal number 34.95 and display the answer in second text box.

The code is doing the calculation little bit ok because

when I enter the value 1000 in first text box it gives answer 34950 in second textbox and when I enter the value 100 in first text box it gives answer 3495.0000000000005 in second text box.

**Please any one tell me what is the problem. is problem is in my jQuery code.

  1. I also want to show the answer always in decimal point.

  2. Answer should always dislply only two digits after decimal point. so How to achieve this too.**

This is my jQuery code.

  $("#id_pvalue").focusout(function() {
        q=$("#id_pvalue").val();
        var ans=q*34.95;
        $("#id_tvalue").val(ans);
  });

Upvotes: 0

Views: 739

Answers (6)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

.. and besides all the above answers, have a look at the following article if you want to understand the limitations of computer-based floating-point arithmetic

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 1

rosscj2533
rosscj2533

Reputation: 9323

While Darin's answer should work, here's another way to limit your value to two decimal places:

var ans=q*34.95;
ans = ans.toFixed(2);

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

The val function returns strings. You need to convert it to a number:

$('#id_pvalue').focusout(function() {
    var q = parseFloat($(this).val());
    if (!isNaN(q)) {
        var ans = Math.round(q * 34.95 * 100) / 100;
        // If you always want to have two decimals after the separator
        // you could use the toFixed function:
        // var ans = (q * 34.95).toFixed(2);
        $('#id_tvalue').val(ans);
    }
});

Upvotes: 2

Jon
Jon

Reputation: 6056

  $("#id_pvalue").focusout(function() {
        var q= parseFloat($("#id_pvalue").val());
        var ans= (q*34.95).toFixed(2);
        $("#id_tvalue").val(ans);
  });

Upvotes: 0

Bobby
Bobby

Reputation: 11576

Sounds to me like the usual Floating Point Issue. For formatting numbers in JavaScript please see this little tutorial.

Upvotes: 2

rahul
rahul

Reputation: 187110

Try

$("#id_pvalue").blur(function() {
    q= parseFloat($(this).val());
    var ans=q*34.95;
    $("#id_tvalue").val(ans);
});

Upvotes: 0

Related Questions