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

Share:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Twitthis
This entry was posted in jQuery, Syndicated. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree