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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

10 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??

Anonymous said...

Thank You!

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

NIMESH JAIN 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