-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #333 from jermspeaks/content/til-regex-decimal-points
Add TIL for 2024-02-15
- Loading branch information
Showing
2 changed files
with
43 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
src/content/writing/2024-02-15-TIL-regex-decimal-points.mdx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
--- | ||
description: "Creating a regular expression for decimal points" | ||
draft: false | ||
pubDate: "2024-02-15" | ||
tags: ["TIL", "programming"] | ||
title: Regex for Decimal Points | ||
coverImage: '../../images/TIL.png' | ||
heroImageAlt: Image from Boston University showing Today I learned | ||
--- | ||
|
||
I needed a regular expression for checking if a number has 1 decimal point. | ||
Here's the regular expression ChatGPT came up with: `/^\d+(\.\d{1})?$/` | ||
|
||
Of course, it wasn't actually the correct requirement. | ||
It needed to check if it's an integer (no decimal points). | ||
And if it is a decimal point, it can be at most one. | ||
|
||
I screwed up and tried to pair two quantifiers together. | ||
So if you have `?` and you want to use `{0,1}`, you can't do `{0.1}?`. | ||
|
||
And I didn' need the group, although in retrospect, using the quantifier on the | ||
group works, but removing the group makes the `?` obsolete. | ||
|
||
Here's what I ultimately came up with. | ||
|
||
```js | ||
function validateToOneOrNoDecimalPoint(number) { | ||
// Regular expression to match numbers with either 0 or 1 decimal point (optional) | ||
const regex = /^\d+\.?\d{0,1}$/; | ||
return regex.test(number); | ||
} | ||
|
||
// Example usage: | ||
console.log(validateToOneOrNoDecimalPoint(3.5)); // true | ||
console.log(validateToOneOrNoDecimalPoint(10)); // true | ||
console.log(validateToOneOrNoDecimalPoint(2.34)); // false (more than one decimal point) | ||
console.log(validateToOneOrNoDecimalPoint(5.)); // true (no decimal point) | ||
console.log(validateToOneOrNoDecimalPoint(5)); // true (no decimal point) | ||
``` | ||
|
||
And I added even more test cases, and used `regex.match` over `regex.test`. | ||
Subtle difference. |