html type = "number": всегда показывать 2 цифры после точки? - PullRequest
0 голосов
/ 14 октября 2019

на входе type="number", я хотел бы показывать 2 цифры после точки, например "2.50"

, если попытаться

<input name="price" type="number" step="0.01" value="2.5">

, то это покажет мне "2.5", а не "2,50 "

У вас есть способ сделать это? HTML5 чистый или с javascript?

Ответы [ 2 ]

0 голосов
/ 14 октября 2019

вам нужно использовать Jquery или JavaScript для того, что вы когда-либо хотите, но это решение в Jquery

Вы не можете перейти более чем на 2 числа

//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="2.50" />

Вы можете просмотреть или отредактировать код Здесь, на JSFiddle

0 голосов
/ 14 октября 2019

Вы можете решить по сценарию, как:

<script type="text/javascript">      
  $(document).ready(function() {
  var num = 2.5;
  var n = num.toFixed(2);
  alert(n);
  });    
</script>    
<script type="text/javascript">      
  $(document).ready(function() {
  var num = 2.500;
  var n = num.toFixed(1);
  alert(n);
  });    
</script>
...