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
Regular Expression to Check Only One Decimal Point
How to Get Full Path of Selected File on Change of <Input Type='File'> Using Javascript, Jquery-Ajax
Onclick JavaScript to Make Browser Go Back to Previous Page
Set Values in Input Type Date and Time in JavaScript
Display Current Date in Dd/Mm/Yyyy Format
Calculate Time Difference Between Two Date in Hh:Mm:Ss JavaScript
Javascript Regex - No White Space At Beginning + Allow Space in the Middle
How to Use Document.Getelementbyid() Method in Typescript
On Click,Redirect to a New Page and Scroll to a Particular Div on That New Page
How to Uncheck All Below Checkboxes When One Checkbox Is Unchecked
How to Print Star Pattern in JavaScript in a Very Simple Manner
How to Hide Select Options With Javascript (Cross Browser)
How to Display an Iframe on Button Click
How to Pass 3 Parameters in Onclick Function .The Parameters Are Inside PHP Tag
Safari Browser Audio.Play() Is Not Working
How to Check a Radio Button in the Table Row Based on That Column Header