HTML5 Number Input - Always show 2 decimal places

Html

Html Problem Overview


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 0.

Html Solutions


Solution 1 - Html

Solved following the suggestions and adding a piece of jQuery to force the format on integers:

parseFloat($(this).val()).toFixed(2)

Solution 2 - Html

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' />

Solution 3 - Html

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'>

Solution 4 - Html

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.

Solution 5 - Html

Based on this answer from @Guilherme Ferreira you can trigger the parseFloat method every time the field changes. Therefore the value always shows two decimal places, even if a user changes the value by manual typing a number.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".floatNumberField").change(function() {
            $(this).val(parseFloat($(this).val()).toFixed(2));
        });
    });
</script>

<input type="number" class="floatNumberField" value="0.00" placeholder="0.00" step="0.01" />

Solution 6 - Html

If you landed here just wondering how to limit to 2 decimal places I have a native javascript solution:

Javascript:

function limitDecimalPlaces(e, count) {
  if (e.target.value.indexOf('.') == -1) { return; }
  if ((e.target.value.length - e.target.value.indexOf('.')) > count) {
    e.target.value = parseFloat(e.target.value).toFixed(count);
  }
}

HTML:

<input type="number" oninput="limitDecimalPlaces(event, 2)" />

Note that this cannot AFAIK, defend against this chrome bug with the number input.

Solution 7 - Html

This works to enforce a max of 2 decimal places without automatically rounding to 2 places if the user isn't finished typing.

function naturalRound(e) {

   let dec = e.target.value.indexOf(".")
   let tooLong = e.target.value.length > dec + 3
   let invalidNum = isNaN(parseFloat(e.target.value))

   if ((dec >= 0 && tooLong) || invalidNum) {
     e.target.value = e.target.value.slice(0, -1)
   }
}

Solution 8 - Html

I know this is an old question, but it seems to me that none of these answers seem to answer the question being asked so hopefully this will help someone in the future.

Yes you can always show 2 decimal places, but unfortunately it can't be done with the element attributes alone, you have to use JavaScript.

I should point out this isn't ideal for large numbers as it will always force the trailing zeros, so the user will have to move the cursor back instead of deleting characters to set a value greater than 9.99

//Use keyup to capture user input & mouse up to catch when user is changing the value with the arrows
    $('.trailing-decimal-input').on('keyup mouseup', function (e) {

        // on keyup check for backspace & delete, to allow user to clear the input as required
        var key = e.keyCode || e.charCode;
        if (key == 8 || key == 46) {
            return false;
        };

        // get the current input value
        let correctValue = $(this).val().toString();

         //if there is no decimal places add trailing zeros
        if (correctValue.indexOf('.') === -1) {
            correctValue += '.00';
        }

        else {

            //if there is only one number after the decimal add a trailing zero
            if (correctValue.toString().split(".")[1].length === 1) {
                correctValue += '0'
            }

            //if there is more than 2 decimal places round backdown to 2
            if (correctValue.toString().split(".")[1].length > 2) {
                correctValue = parseFloat($(this).val()).toFixed(2).toString();
            }
        }

        //update the value of the input with our conditions
        $(this).val(correctValue);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="my-number-input" class="form-control trailing-decimal-input" type="number" min="0.01" step="0.01" value="0.00" />

Solution 9 - Html

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().

Solution 10 - Html

The top answer gave me the solution but I didn't like that the user input was changed immediately so I added delay which in my opinion contributes to a better user experience

var delayTimer;
function input(ele) {
    clearTimeout(delayTimer);
    delayTimer = setTimeout(function() {
       ele.value = parseFloat(ele.value).toFixed(2).toString();
    }, 800); 
}

<input type='number' oninput='input(this)'>

https://jsfiddle.net/908rLhek/1/

Solution 11 - Html

My preferred approach, which uses data attributes to hold the state of the number:

const el = document.getElementById('amt');
// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)

// react to keys
el.addEventListener('onkeyup', ev => {

  // user cleared field
  if (!ev.target.value) ev.target.dataset.val = ''

  // non num input
  if (isNaN(ev.key)) {

    // deleting
    if (ev.keyCode == 8)

      ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)

    // num input
  } else ev.target.dataset.val += ev.key

  ev.target.value = parseFloat(ev.target.dataset.val) / 100

})

<input id="amt" type='number' step='0.01' />

Solution 12 - Html

import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'replace'
})

export class ReplacePipe implements PipeTransform {
    transform(value: any): any {
        value = String(value).toString();
        var afterPoint = '';
        var plus = ',00';
        if (value.length >= 4) {
            if (value.indexOf('.') > 0) {
                afterPoint = value.substring(value.indexOf('.'), value.length);
                var te = afterPoint.substring(0, 3);
                if (te.length == 2) {
                    te = te + '0';
                }
            }
            if (value.indexOf('.') > 0) {
                if (value.indexOf('-') == 0) {
                    value = parseInt(value);
                    if (value == 0) {
                        value = '-' + value + te;
                        value = value.toString();
                    }
                    else {
                        value = value + te;
                        value = value.toString();
                    }
                }
                else {
                    value = parseInt(value);
                    value = value + te;
                    value = value.toString();
                }
            }
            else {
                value = value.toString() + plus;
            }
            var lastTwo = value.substring(value.length - 2);
            var otherNumbers = value.substring(0, value.length - 3);
            if (otherNumbers != '')
                lastTwo = ',' + lastTwo;
            let newValue = otherNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + lastTwo;
            parseFloat(newValue);
            return `${newValue}`;
        }
}
}

Solution 13 - Html

ui-number-mask for angular, https://github.com/assisrafael/angular-input-masks

only this:

<input ui-number-mask ng-model="valores.irrf" />

If you put value one by one....

need: 120,01

digit per digit

 = 0,01
 = 0,12
 = 1,20
 = 12,00
 = 120,01 final number.

Solution 14 - Html

Take a look at this:

 <input type="number" step="0.01" />

Solution 15 - Html

This is the correct answer:

<input type="number" step="0.01" min="-9999999999.99" max="9999999999.99"/>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuilherme FerreiraView Question on Stackoverflow
Solution 1 - HtmlGuilherme FerreiraView Answer on Stackoverflow
Solution 2 - HtmlRich BradshawView Answer on Stackoverflow
Solution 3 - HtmlDissident RageView Answer on Stackoverflow
Solution 4 - Htmllittle_birdieView Answer on Stackoverflow
Solution 5 - HtmlmhellmeierView Answer on Stackoverflow
Solution 6 - HtmlStephen PaulView Answer on Stackoverflow
Solution 7 - HtmlSuperCodeBrahView Answer on Stackoverflow
Solution 8 - HtmlVernoView Answer on Stackoverflow
Solution 9 - HtmlkblocksView Answer on Stackoverflow
Solution 10 - HtmlStanView Answer on Stackoverflow
Solution 11 - Htmlnikk wongView Answer on Stackoverflow
Solution 12 - HtmlRamakanthReddy KowdampalliView Answer on Stackoverflow
Solution 13 - HtmlRaphael VitorView Answer on Stackoverflow
Solution 14 - HtmlchrisView Answer on Stackoverflow
Solution 15 - HtmlAlexView Answer on Stackoverflow