Round off Decimal to 2 places in jQuery

I was recently working on a requirement where a textbox value had to be rounded off to 2 decimal digits and ‘$’ appended in front of it. Here’s how to achieve it

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Round to 2 Decimal Places</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$('input#txtNum').blur(function() {
var amt = parseFloat(this.value);
$(this).val('$' + amt.toFixed(2));
});

});
</script>
</
head>
<
body>
Type a decimal number in the TextBox and hit Tab
<br />
<
input id="txtNum" type="text" />
</
body>
</
html>

Here we use the toFixed() which Formats a number using fixed-point notation. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

image

After the TextBox loses focus

image

See a Live Demo

9 comments:

  1. Thanks for your solution, helped me with the same problem.

    ReplyDelete
  2. I've been using some code which basically multiplies by 100, rounds using Math.round() and divides by 100 to get 2 decimal places.

    This is incredibly simple instead.

    Thanks.

    ReplyDelete
  3. You are welcome. Thanks for the feedback!

    ReplyDelete
  4. I simply copy pasted your code, but the output i recieved is "$NaN".
    Is there any solution??

    ReplyDelete
  5. The only problem with your solution is that tofixed round in a certain way.

    for example
    3.45 : 3.4
    3.55 : 3.6

    This function always rounds to the closest even number

    ReplyDelete
  6. Hi, This function is somewhat peculiar in in it's functioning like it will give u result correct till certain values and for some it will give wrong values like say till 14.525 it will round correct to 14.53 but afterwards it starts giving wrong values and 16.525 gives 15.52 which is not in sync with expected results. is there other better function than this or any fix has come for this?

    ReplyDelete
  7. How can we make sure that user should enter only numeric along with one decimal point only

    ReplyDelete
  8. The code block gives different results in different browsers.
    For eg. If i enter 0.007 in IE8 it returns 0.00 and in Chrome it returns 0.01

    ReplyDelete