【发布时间】:2014-05-03 16:18:05
【问题描述】:
有没有办法将input[type='number'] 值格式化为始终显示 2 位小数?
示例:我想查看 0.00 而不是 0。
【问题讨论】:
标签: html
有没有办法将input[type='number'] 值格式化为始终显示 2 位小数?
示例:我想查看 0.00 而不是 0。
【问题讨论】:
标签: html
你不能仅仅使用 HTML 来做到这一点,但你可能已经做了一半:
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
【讨论】:
看看this:
<input type="number" step="0.01" />
【讨论】:
使用step attribute will enable it。它不仅决定了它应该循环多少,还决定了允许的数量。使用step="0.01" 应该可以解决问题,但这可能取决于浏览器如何遵守标准。
<input type='number' step='0.01' value='5.00'>
【讨论】:
input[type="text"] 与 input[type="number"] 附带的所有本机花里胡哨彻底重新实现它,或者将这个字段换成另一个以显示取决于元素的值状态。
按照建议解决并添加一段 jQuery 以强制整数格式:
parseFloat($(this).val()).toFixed(2)
【讨论】:
robot_speed = parseFloat(robot_speed).toFixed(2)
change 方法中,以在每次字段更改时触发它:stackoverflow.com/a/58502237/2056125
toFixed 返回的字符串在某些情况下可能会导致问题。
使用 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 的上述答案。
【讨论】:
type 属性是number 还是text 来检查这一点。如果它返回 text,即使 HTML 写为 number,则浏览器不支持该类型,并且将此行为挂钩是适当的操作。
这是正确答案:
<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" />
【讨论】:
parseFloat($(this).val()).toFixed(2).toString() 是重复的,因为parseFloat($(this).val()).toFixed(2) 已经将值作为字符串返回
ui-number-mask 用于角度,https://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);
});
注意:出于某种原因,即使输入是“数字”类型,jQuery val() 也会返回一个字符串。因此parseFloat()。
【讨论】:
根据@Guilherme Ferreira 的this 回答,您可以在每次字段更改时触发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" />
【讨论】:
change() 函数将在用户输入和提交按钮单击之间的一小段时间内被触发。因此,这应该不是问题。
如果您来到这里只是想知道如何限制为 2 位小数我有一个原生 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,用数字输入来防御 this chrome 错误。
【讨论】:
最佳答案给了我解决方案,但我不喜欢立即更改用户输入,因此我添加了延迟,我认为这有助于改善用户体验
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)'>
【讨论】: