在type="number"
输入中,我想在点后显示“ 2.50”之类的2位数字
如果尝试
<input name="price" type="number" step="0.01" value="2.5">
这告诉我“ 2.5”而不是“ 2.50”
您有执行此操作的方法吗? HTML5 pure或javascript吗?
答案 0 :(得分:1)
您需要使用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" />
您可以预览或编辑代码Here on JSFiddle
答案 1 :(得分:0)
您可以通过脚本来解决:
<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>