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 s开发者_运维知识库econd text box.
**Please any one tell me what is the problem. is problem is in my jQuery code.
I also want to show the answer always in decimal point.
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);
});
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);
Sounds to me like the usual Floating Point Issue. For formatting numbers in JavaScript please see this little tutorial.
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);
}
});
.. 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
Try
$("#id_pvalue").blur(function() {
q= parseFloat($(this).val());
var ans=q*34.95;
$("#id_tvalue").val(ans);
});
$("#id_pvalue").focusout(function() {
var q= parseFloat($("#id_pvalue").val());
var ans= (q*34.95).toFixed(2);
$("#id_tvalue").val(ans);
});
精彩评论