Javascript Math Rounding

22,305

Solution 1

You can use Math.floor() function to 'round down'

$("#s").text(Math.floor((new Date - x) / 60000 + "Minutes Wasted"));

or Math.ceil(), which 'round up'

$("#s").text(Math.ceil((new Date - x) / 60000 + "Minutes Wasted"));

or Math.round(), which round either up or down, where it's closer to:

$("#s").text(Math.round((new Date - x) / 60000 + "Minutes Wasted"));

Solution 2

Math.round?

See http://www.w3schools.com/jsref/jsref_obj_math.asp

Share:
22,305
0x60
Author by

0x60

Just a kid with a computer.

Updated on February 16, 2020

Comments

  • 0x60
    0x60 about 4 years

    Possible Duplicate:
    Is JavaScript's Math broken?

    Okay, I have this script:

    var x = new Date;
    setInterval(function() {
        $("#s").text((new Date - x) / 60000 + "Minutes Wasted");
    }, 30000);
    

    It works perfectly fine. Except it sometimes gives me an answer like 4.000016666666666. How can I round that? If I have to rewrite the script, that is okay. Thanks!

  • Martijn
    Martijn about 13 years
    Math.Round (sic) is not going to work; Round is not a constructor so doesn't start with a capital R.