isFloat
Checks if a number is a floating-point number (i.e. not an integer).
1/**
2 * Checks if a number is a floating-point number (i.e. not an integer).
3 *
4 * @param num - The number to check.
5 * @returns True if the number is a float, false if it's an integer or invalid.
6 */
7export function isFloat(num: number): boolean {
8 return Number.isFinite(num) && Math.floor(num) !== num;
9}
Accurate Float Detection
Reliably distinguishes floats from integers using both
Number.isFinite
and a strict comparison.Handles Edge Cases
Excludes
NaN
,Infinity
, and non-numeric inputs, improving robustness.Minimal and Performant
Lightweight logic with excellent performance for frequent runtime checks.
Tests | Examples
1test('isFloat - float number', () => {
2 expect(isFloat(3.14)).toBe(true);
3});
4
5test('isFloat - integer number', () => {
6 expect(isFloat(5)).toBe(false);
7});
8
9test('isFloat - negative float', () => {
10 expect(isFloat(-2.718)).toBe(true);
11});
12
13test('isFloat - negative integer', () => {
14 expect(isFloat(-4)).toBe(false);
15});
16
17test('isFloat - zero', () => {
18 expect(isFloat(0)).toBe(false);
19});
20
21test('isFloat - NaN', () => {
22 expect(isFloat(NaN)).toBe(false);
23});
24
25test('isFloat - Infinity', () => {
26 expect(isFloat(Infinity)).toBe(false);
27});
28
29test('isFloat - very small float', () => {
30 expect(isFloat(1e-8)).toBe(true);
31});
Common Use Cases
Data Validation
Ensure numeric inputs are fractional when required (e.g., percentage weights, rates).
Form Handling
Accept or reject user input based on whether it's a whole number or float.
Conditional Formatting
Display different formatting or rounding rules depending on whether a number is a float.
Scientific or Statistical Applications
Detect non-integer values for specialized processing like interpolation or approximation.