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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

9 comments:

Anonymous said...

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

Mike said...

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.

Suprotim Agarwal said...

You are welcome. Thanks for the feedback!

Anonymous said...

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

Unknown said...

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

Alok said...

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?

Anonymous said...

thanku sir

Dorababu said...

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

Unknown said...

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