HTML5 숫자 입력-항상 소수점 이하 2 자리 표시
input[type='number']
항상 소수점 이하 두 자리를 표시 하도록 값을 형식화하는 방법이 있습니까?
예 : "0.00"
대신 보고 싶습니다 0
.
감사
정말 할 수는 없지만 중간 단계는 다음과 같을 수 있습니다.
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
제안 사항에 따라 해결하고 jQuery를 추가하여 정수 형식을 강제 적용 parseFloat($(this).val()).toFixed(2)
은 Using step
속성은 그것을 가능하게 할 것이다 . 순환해야하는 양뿐만 아니라 허용되는 숫자도 결정합니다. 사용 하는 것이 트릭을 수행 step="0.01"
해야 하지만 이것은 브라우저가 표준을 어떻게 준수하는지에 따라 달라질 수 있습니다.
<input type='number' step='0.01' value='5.00'>
사용하는 솔루션 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의 위 답변을 사용할 것입니다.
이것은 소수점 두 자리에 대해 .toFixed (2) 함수를 사용하는 JQuery의 빠른 포맷터입니다.
<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 ()
이것이 정답입니다.
<input type="number" step="0.01" min="-9999999999.99" max="9999999999.99"/>
이것은 사용자가 입력을 완료하지 않은 경우 자동으로 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)
}
}
I know this is an old question, but it seems to me that none of these answers seem to answer the question being asked so hopefully this will help someone in the future.
Yes you can always show 2 decimal places, but unfortunately it can't be done with the element attributes alone, you have to use JavaScript.
I should point out this isn't ideal for large numbers as it will always force the trailing zeros, so the user will have to move the cursor back instead of deleting characters to set a value greater than 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-mask for angular, https://github.com/assisrafael/angular-input-masks
only this:
<input ui-number-mask ng-model="valores.irrf" />
if u put value one by one....
need: 120,01
digit per digit
= 0,01
= 0,12
= 1,20
= 12,00
= 120,01 final number.
My preferred approach, which uses data
attributes to hold the state of the number:
<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
})
Take a look at this:
<input type="number" step="0.01" />
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}`;
}
}
}
참고URL : https://stackoverflow.com/questions/22641074/html5-number-input-always-show-2-decimal-places
'program tip' 카테고리의 다른 글
멀티 파트 / 양식 데이터의 예 (0) | 2020.09.10 |
---|---|
HttpClient에서 await를 사용한 비동기 호출이 반환되지 않음 (0) | 2020.09.10 |
async componentDidMount () 사용이 좋은가요? (0) | 2020.09.10 |
빈 배열 항목을 건너 뛰면서 배열을 내파하려면 어떻게해야합니까? (0) | 2020.09.09 |
인간 친화적 인 상대 날짜 형식을위한 자바 스크립트 라이브러리 (0) | 2020.09.09 |