Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions String/IsNumeric.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* @function isNumeric
* @description Checks whether a string represents a valid numeric value.
* Supports integers, floats, and negative numbers.
* @param {string} str - The input string to check
* @returns {boolean} - True if the string is numeric, false otherwise
* @see https://en.wikipedia.org/wiki/Numeric_string
* @example isNumeric("123") => true
* @example isNumeric("-45.6") => true
* @example isNumeric("abc") => false
* @example isNumeric("12.3.4") => false
*/
const isNumeric = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Input must be a string')
}
if (str.trim() === '') return false
return !isNaN(str) && !isNaN(parseFloat(str))
}

export { isNumeric }
51 changes: 51 additions & 0 deletions String/test/IsNumeric.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { isNumeric } from '../IsNumeric.js'

describe('isNumeric', () => {
test("isNumeric('123') returns true", () => {
expect(isNumeric('123')).toBe(true)
})

test("isNumeric('-45.6') returns true", () => {
expect(isNumeric('-45.6')).toBe(true)
})

test("isNumeric('0') returns true", () => {
expect(isNumeric('0')).toBe(true)
})

test("isNumeric('3.14') returns true", () => {
expect(isNumeric('3.14')).toBe(true)
})

test("isNumeric('abc') returns false", () => {
expect(isNumeric('abc')).toBe(false)
})

test("isNumeric('12.3.4') returns false", () => {
expect(isNumeric('12.3.4')).toBe(false)
})

test("isNumeric('') returns false", () => {
expect(isNumeric('')).toBe(false)
})

test("isNumeric(' ') returns false", () => {
expect(isNumeric(' ')).toBe(false)
})

test("isNumeric('123abc') returns false", () => {
expect(isNumeric('123abc')).toBe(false)
})

test("isNumeric('-0') returns true", () => {
expect(isNumeric('-0')).toBe(true)
})

test('throws TypeError for non-string input', () => {
expect(() => isNumeric(123)).toThrow(TypeError)
})

test('throws TypeError for null input', () => {
expect(() => isNumeric(null)).toThrow(TypeError)
})
})
Loading