6 examples of 'regex for decimal number upto 2 places' in JavaScript

Every line of 'regex for decimal number upto 2 places' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
61function getRegex (isDecimal: boolean): RegExp {
62 return new RegExp(
63 isDecimal
64 ? `^(0|[1-9]\\d*)(\\${KEYS.DECIMAL}\\d*)?$`
65 : '^(0|[1-9]\\d*)$'
66 );
67}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

3function decimalPlaces(num) {
4 var match = ("" + num).match(/(?:\.(\d+))?$/);
5 /* istanbul ignore if */
6 if (!match) {
7 return 0;
8 }
9
10 // Number of digits right of decimal point.
11 return match[1] ? match[1].length : 0;
12}
71function decimalPlaces( number ) {
72 const match = ( '' + number ).match( /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/ );
73 if ( ! match ) {
74 return 0;
75 }
76 return Math.max( 0, ( match[ 1 ] ? match[ 1 ].length : 0 ) - ( match[ 2 ] ? +match[ 2 ] : 0 ) );
77}
68function removeDecimal(num) {
69 const re = new RegExp('^-?\\d+');
70 return num.toString().match(re)[0];
71}
61function groupDigits(num) {
62 var ret = "";
63 while (num.length > 3) {
64 ret = "." + num.slice(num.length - 3) + ret;
65 num = num.substring(0, num.length - 3);
66 }
67 ret = num + ret;
68
69 return ret;
70}
7export default function formatDecimal (value: string): string {
8 // We can do this by adjusting the regx, however for the sake of clarity
9 // we rather strip and re-add the negative sign in the output
10 const isNegative = value[0].startsWith('-');
11 const matched = isNegative
12 ? value.substr(1).match(NUMBER_REGEX)
13 : value.match(NUMBER_REGEX);
14
15 return matched
16 ? `${isNegative ? '-' : ''}${matched.join(',')}`
17 : value;
18}

Related snippets