HTML5数字输入-总是显示小数点后2位

有没有什么方法可以格式化 input[type='number']值,使其始终显示小数点后2位?

例如: 我想看到 0.00而不是 0

307547 次浏览

仅使用 HTML 无法做到这一点,但半途而废的步骤可能是:

<input type='number' step='0.01' value='0.00' placeholder='0.00' />

看看 这个:

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

使用 step属性将启用它。它不仅决定了它应该循环多少,而且还决定了允许的数字。使用 step="0.01"应该可以做到这一点,但这可能取决于浏览器如何遵守标准。

<input type='number' step='0.01' value='5.00'>

按照建议并添加一段 jQuery 来强制整数的格式,解决了这个问题:

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

使用 input="number" step="0.01"的解决方案在 Chrome 中非常适合我,但是在一些浏览器中不能工作,特别是在我的情况下,Frontmotion Firefox 35。.我必须支持。

我的解决方案是使用 Igor Escobar 的 jQuery Mask 插件来实现 jQuery,如下所示:

$(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">

这个工作得很好,当然之后应该检查提交的值:)注意,如果我不需要为了浏览器兼容性这样做,我会使用@Rich Bradshaw 的上述答案。

正确答案是:

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

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}`;
}
}
}

如果用户没有完成输入,这种方法可以强制执行最多2个小数位,而不会自动四舍五入到2位。

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)
}
}

我知道这是一个古老的问题,但在我看来,这些答案似乎都没有回答问题,所以希望这将有助于在未来的人。

是的,您总是可以显示小数点后2位,但不幸的是,它不能单独使用元素属性,必须使用 JavaScript。

我应该指出,这对于大数字来说并不理想,因为它总是强制后面的零,所以用户必须将光标移回来,而不是删除字符来设置大于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" />

角度的 ui-number-maskhttps://github.com/assisrafael/angular-input-masks

只有这个:

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

如果你把价值一个接一个... 。

need: 120,01

每位数字的数字

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

我首选的方法是使用 data属性来保存数字的状态:

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

这是 JQuery 中的一个快速格式化程序,使用 .toFixed(2)函数处理两个小数位。

<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));
}

缺点: 每次更改输入号码以重新格式化它时,都必须调用这个函数。

// 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);
});

注意: 由于某种原因,即使输入类型为“ number”,jQuery val()也会返回一个字符串。所以才有了 parseFloat()

基于来自@Guilherme Ferreira 的 这个答案,您可以在每次字段更改时触发 parseFloat方法。因此,该值始终显示两个小数位,即使用户通过手动键入一个数字来更改该值。

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

如果你来到这里只是想知道如何 小数点后两位我有一个本地的 javascript 解决方案:

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)" />

请注意,这不能 AFAIK,防御 这个铬错误与数字输入。

顶部的答案给了我解决方案,但我不喜欢用户输入立即改变,所以我增加了延迟,在我看来有助于更好的用户体验

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/