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

3 Answers

0 votes
let d = 241278.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 = 2735423.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).
// Node.js uses JavaScript's Number type, which behaves like a double.
// Uses Number.isInteger for clean cases and a small tolerance for precision.
// -----------------------------------------------------------------------------
function isInteger(value) {
    const epsilon = 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) {
    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() {
    // Example input values (Node.js numbers behave like doubles)
    const a = 42.0;                 // integer-like
    const b = 71.00000000001;       // floating-point due to tiny fraction
    const c = 89.0000000000001;     // integer-like
    const d = -6.0;                 // negative integer-like
    const e = 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: 71.00000000001
Result: The value contains a floating‑point number.

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

Checking value: -6
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

...