Restrict to 2 Decimal Places in Keypress of a Text Box

Restrict to 2 decimal places in keypress of a text box?

You were almost there. Just check that there are no more than 2 characters after the decimal.

UPDATE 1 - check carat position to allow character insertion before the decimal.

UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.

 function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}

//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}

http://jsfiddle.net/S9G8C/1/

http://jsfiddle.net/S9G8C/203/

Only allow numbers and one dot with 2 decimal places restriction in keypress vuejs

Working example: https://jsfiddle.net/0s14cbqx/

In template:

<input placeholder="Name a price" v-model="price" @keypress="onlyForCurrency">

In js:

data(){
return{
price:null
}
},
methods: {
onlyForCurrency ($event) {
// console.log($event.keyCode); //keyCodes value
let keyCode = ($event.keyCode ? $event.keyCode : $event.which);

// only allow number and one dot
if ((keyCode < 48 || keyCode > 57) && (keyCode !== 46 || this.price.indexOf('.') != -1)) { // 46 is dot
$event.preventDefault();
}

// restrict to 2 decimal places
if(this.price!=null && this.price.indexOf(".")>-1 && (this.price.split('.')[1].length > 1)){
$event.preventDefault();
}
}
}

In this way, users only can key in numbers and one dot and can't key in anything after 2 decimal places.

Limit input field to two decimal places - Angular 5

First create Directive for limit the two decimal places in typescript like this:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
console.log(this.el.nativeElement.value);
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
const position = this.el.nativeElement.selectionStart;
const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}

Inject Directive in your app.module.ts.
In your html use that directive like this:

<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>

Here is working example in Angular 4/5/6: Limit Two decimal places number validation

Hope this will help you!!!!

Allow only 2 decimal points entry to a textbox using jquery?

You could do it without regex:

var dec = parseFloat($("#amountId").val(),10).toFixed(2);


Related Topics



Leave a reply



Submit