I am trying to use a regular expression to validate decimal values . I wrote below regular expression but it does not allowing first decimal with value like a .5 or .6 or .1
Regular Exp : /^\d[0-9]{0,13}(\.\d{1,2})?$/
Rules :
Example - Valid inputs
Example - invalid inputs
const valid = [
"0",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^\d[0-9]{0,13}(\.\d{1,2})?$/
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));
A regular expression for a decimal number needs to checks for one or more numeric characters (0-9) at the start of the string, followed by an optional period, and then followed by zero or more numeric characters (0-9). This should all be followed by an optional plus or minus sign.
html. The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in above syntax using the '.
Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.
To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.
I believe the following regex should meet all of your criteria:
^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)
first case: 1-13 digits followed either by nothing or by a "." followed by one or two digits
second case: a "." followed by a non zero digit and at most one other digit
const valid = [
"0",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)/
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));
i think this should do most of your requirment but not all of them, limit to 9 decimal places
( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ )
and this one with no decimal limit
( /^(\d+\.?\d*|\.\d+)$/ )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With