有什么办法可以将input[type='number']值格式化为始终显示2个小数位?
范例:我想0.00代替0。
有什么办法可以将input[type='number']值格式化为始终显示2个小数位?
范例:我想0.00代替0。
Answers:
解决了以下建议,并添加了一段jQuery以强制将格式设置为整数:
parseFloat($(this).val()).toFixed(2)
change方法中,以在每次字段更改时触发它:stackoverflow.com/a/58502237/2056125
您不能真正做到,但您可能需要做的一半:
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
使用该step属性将启用它。它不仅确定应该循环的次数,而且还确定允许的数字。使用step="0.01" 应该可以解决问题,但这可能取决于浏览器如何遵守标准。
<input type='number' step='0.01' value='5.00'>
input[type="text"]带有完全重新实现的所有本机铃声input[type="number"],或者将这个字段换成另一个以根据元素状态显示值。
使用的解决方案input="number" step="0.01"对我来说在Chrome中非常有用,但是在某些浏览器中不起作用,特别是在我的情况下特别是Frontmotion Firefox 35 ..我必须支持。
我的解决方案是使用Igor Escobar的jQuery Mask插件来实现jQuery,如下所示:
<script src="/your/path/to/jquery-mask.js"></script>
<script>
$(document).ready(function () {
$('.usd_input').mask('00000.00', { reverse: true });
});
</script>
<input type="text" autocomplete="off" class="usd_input" name="dollar_amt">
这很好用,当然以后应该检查提交的值:)注意,如果我不必这样做是为了与浏览器兼容,我将使用@Rich Bradshaw的上述答案。
type属性是否为number或来进行检查text。如果text即使HTML是这样编写的,也返回它,number则表明浏览器不支持该类型,将这种行为挂接到它上是适当的操作。
基于此,从@Guilherme费雷拉回答您可以触发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个小数位,而不会自动舍入到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解决方案:
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,请使用数字输入来防御此 Chrome错误。
我知道这是一个古老的问题,但是在我看来,这些答案似乎都无法回答所提出的问题,因此希望这对以后的人有所帮助。
是的,您始终可以显示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" />
这是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()。
我的首选方法是使用data属性来保存数字的状态:
<input type='number' step='0.01'/>
// 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
})
最佳答案为我提供了解决方案,但我不喜欢立即更改用户输入,因此我增加了延迟,我认为这有助于改善用户体验
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)'>
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}`;
}
}
}
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.
robot_speed = parseFloat(robot_speed).toFixed(2)