Limit Number of Digits After Decimals in Text Input

Limit number of digits after decimals in text input

As I am not aware of any way to do it in HTML…

Here is how I'll do it with some JavaScript, using a RegEx to delete the extra decimals:

var myInput = document.querySelector('#fixed2');myInput.addEventListener("keyup", function(){  myInput.value = myInput.value.replace(/(\.\d{2})\d+/g, '$1');});
<input id="fixed2" type="text" />

Limit number of digits before and after decimals in text field in jetpack compose

The first step would be to set keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) for the TextField. This will open numeric keypad when the TextField is focused.

Now the problem is that TextField doesn't do any validation by itself (unlike the EditText with inputType="number"). User can type any character present on the keyboard (like commas, spaces, dashes, and even multiple decimals). You need to do all this validation by yourself.

Try this code:

var number by remember { mutableStateOf("") }
TextField(
value = number,
onValueChange = { number = getValidatedNumber(it) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
fun getValidatedNumber(text: String): String {
// Start by filtering out unwanted characters like commas and multiple decimals
val filteredChars = text.filterIndexed { index, c ->
c in "0123456789" || // Take all digits
(c == '.' && text.indexOf('.') == index) // Take only the first decimal
}
// Now we need to remove extra digits from the input
return if(filteredChars.contains('.')) {
val beforeDecimal = filteredChars.substringBefore('.')
val afterDecimal = filteredChars.substringAfter('.')
beforeDecimal.take(3) + "." + afterDecimal.take(2) // If decimal is present, take first 3 digits before decimal and first 2 digits after decimal
} else {
filteredChars.take(3) // If there is no decimal, just take the first 3 digits
}
}

I haven't tested this code but I think it should work for most of the cases. It will make sure that final input doesn't exceed the original constraints but it might lead to some unexpected behavior. For example:

  • If the current text is "123.45" and the user places the cursor after decimal and removes the decimal. In that case the new text will become "123" i.e. "45" will get removed because "12345" breaks the "3 digits before decimal constraint".
  • If the current text is "123" and user places cursor at the start and types "4", the next text will be "412". "3" will be removed.

For these corner cases where user changes cursor position and types stuff, you will have to decide what the correct behavior should be (like in my 1st example, you might choose to not allow decimal removal and keep the original text). You will have to add such conditions in the getValidatedNumber function based on your exact requirements. One workaround that I some times use here is to disable cursor position change i.e. cursor will always remain at the end and cannot be brought to arbitrary indices.

Limit numbers before and after decimal point on input number

You can add a onchange event on the input field and call a function that validates the current input value using regex and communicate same to the user.

Regex : ^[0-9]{0,3}.?[0-9]{0,3}$


JS Code to validate:

function validateNumberInput(inputNumber){
return number.search(/^[0-9]{0,3}.?[0-9]{0,3}$/) == 0 ? true : false;
}

Also you can write a directive in angular that can handle the same.

Allow 2 decimal places in input type=number

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

How to limit set the maximum decimal places of a number as 8 decimal places in React using javascript

You could do a little trick where you multiply the number by 1e8 and then round it, then divide by 1e8.

For example:

const setAmount = console.log;
const handleAmount = (value) => {
const numberAmount = Number(value);
const rounded = Math.round(numberAmount * 1e8) / 1e8;
setAmount(rounded);
};
handleAmount(10.21231123124124124142);
handleAmount(7.242);
handleAmount(80.00000000000);
handleAmount(21.00000001);

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!!!!



Related Topics



Leave a reply



Submit