Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
To recap, you can use the . toFixed() method to limit decimal places.
You can also use a decimal value: for example, a step of 0.3 will allow values such as 0.3, 0.6, 0.9 etc, but not 1 or 2. Now you don't get a validation error. Yay! Also note that if you only want to accept positive numbers, you'll want to add min=”0″.
If we want to round 4.732 to 2 decimal places, it will either round to 4.73 or 4.74. 4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74).
You can't really do this just with HTML, but you a halfway step might be:
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
Solved following the suggestions and adding a piece of jQuery to force the format on integers:
parseFloat($(this).val()).toFixed(2)
Using the step
attribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01"
should do the trick but this may depend on how the browser adheres to the standard.
<input type='number' step='0.01' value='5.00'>
The solutions which use input="number"
step="0.01"
work great for me in Chrome, however do not work in some browsers, specifically Frontmotion Firefox 35 in my case.. which I must support.
My solution was to jQuery with Igor Escobar's jQuery Mask plugin, as follows:
$(document).ready(function () {
$('.usd_input').mask('00000.00', { reverse: true });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<input type="text" autocomplete="off" class="usd_input" name="dollar_amt">
This works well, of course one should check the submitted value afterward :) NOTE, if I did not have to do this for browser compatibility I would use the above answer by @Rich Bradshaw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With