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.
After the TextBox loses focus
See a Live Demo
From DevCurry
