How to check whether a floating-point variable is an integer (has no fractional part) in TypeScript

3 Answers

0 votes
let d: number = 9241278.0;

if (d == Math.floor(d)) {
    console.log("The double variable contains an integer");
}
else {
    console.log("The double variable contains a floating point");
}



/*
run:

"The double variable contains an integer" 

*/

 



answered Mar 7, 2024 by avibootz
0 votes
const d: number = 235423.0; 

console.log(Number.isInteger(d)); 



/*
run:

true 

*/

 



answered Mar 7, 2024 by avibootz
0 votes
// -----------------------------------------------------------------------------
// Determines whether a number contains an integer (no fractional part).
// TypeScript numbers behave like JavaScript's Number type (a double‑precision float).
// Uses Number.isInteger for clean cases and a small tolerance for precision issues.
// -----------------------------------------------------------------------------
function isInteger(value: number): boolean {
    const epsilon: number = 1e-12;

    // Number.isInteger handles exact integer values efficiently.
    // For floating‑point edge cases, compare against a rounded version.
    return Number.isInteger(value) || Math.abs(value - Math.round(value)) < epsilon;
}

// -----------------------------------------------------------------------------
// Prints a descriptive message for the given number.
// -----------------------------------------------------------------------------
function printCheck(value: number): void {
    console.log(`Checking value: ${value}`);

    if (isInteger(value)) {
        console.log("Result: The value contains an integer.\n");
    } else {
        console.log("Result: The value contains a floating‑point number.\n");
    }
}

// -----------------------------------------------------------------------------
// Entry point demonstrating several example values.
// -----------------------------------------------------------------------------
function main(): void {
    // Example input values (TypeScript numbers behave like doubles)
    const a: number = 42.0;                 // integer-like
    const b: number = 42.00000000001;       // floating-point due to tiny fraction
    const c: number = 89.0000000000001;     // integer-like
    const d: number = -7.0;                 // negative integer-like
    const e: number = 3.14;                 // floating-point

    // Run checks
    printCheck(a);
    printCheck(b);
    printCheck(c);
    printCheck(d);
    printCheck(e);
}

main();



/*
run:

Checking value: 42
Result: The value contains an integer.

Checking value: 42.00000000001
Result: The value contains a floating‑point number.

Checking value: 89.0000000000001
Result: The value contains an integer.

Checking value: -7
Result: The value contains an integer.

Checking value: 3.14
Result: The value contains a floating‑point number.

*/

 



answered Sep 10 by avibootz

Related questions

...