Is there\'s any way to format an input[type=\'number\']
value to always show 2 decimal places?
Example: I want to see 0.00
instead of
This is a quick formatter in JQuery using the .toFixed(2)
function for two decimal places.
<input class="my_class_selector" type='number' value='33'/>
// if this first call is in $(document).ready() it will run
// after the page is loaded and format any of these inputs
$(".my_class_selector").each(format_2_dec);
function format_2_dec() {
var curr_val = parseFloat($(this).val());
$(this).val(curr_val.toFixed(2));
}
Cons: you have to call this every time the input number is changed to reformat it.
// listener for input being changed
$(".my_class_selector").change(function() {
// potential code wanted after a change
// now reformat it to two decimal places
$(".my_class_selector").each(format_2_dec);
});
Note: for some reason even if an input is of type 'number' the jQuery val()
returns a string. Hence the parseFloat()
.
You can't really, but you a halfway step might be:
<input type='number' step='0.01' value='0.00' placeholder='0.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:
<script src="/your/path/to/jquery-mask.js"></script>
<script>
$(document).ready(function () {
$('.usd_input').mask('00000.00', { reverse: true });
});
</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.