npm.nicfv.com

    JavaScript Math Oddities

    Sometimes, JavaScript does weird math! Try adding 0.1 + 0.2 in your NodeJS terminal. What did you get?

    Hint: It's not 0.3!

    The function SMath.approx() is an attempt to mitigate some of the issues that arise when doing arithmetic with non-whole numbers.

    Follow these steps to create a new project workspace and install the smath dependency to run this example.

    # Create and open project folder
    mkdir JavaScript_Math_Oddities_demo
    cd JavaScript_Math_Oddities_demo
    # Initialize project and install dependencies
    npm init -y
    npm i smath@1.12.1
    # Create and open source file
    touch "JavaScript Math Oddities.mjs"
    open "JavaScript Math Oddities.mjs"

    Copy and paste this source code into JavaScript Math Oddities.mjs.

    import { SMath } from 'smath';

    // Determine the value of 0.1 + 0.2 using vanilla JavaScript and SMath
    console.log('0.1 + 0.2 == 0.3 is ' + (0.1 + 0.2 == 0.3));
    console.log('SMath.approx(0.1 + 0.2, 0.3) is ' + SMath.approx(0.1 + 0.2, 0.3));

    In JavaScript_Math_Oddities_demo/, execute JavaScript Math Oddities.mjs with NodeJS to generate an output.

    node "JavaScript Math Oddities.mjs"
    

    You should expect to see an output similar to the one below.

    0.1 + 0.2 == 0.3 is false
    SMath.approx(0.1 + 0.2, 0.3) is true
    
    MMNEPVFCICPMFPCPTTAAATR