Simple question - how do you round a number in JavaScript?

Discussion in 'JavaScript' started by norfstar, Nov 28, 2007.

  1. #1
    Say for example I have the number 54.729401 - how in JavaScript can I round it to an integer (55) or to 2 decimal places for currency format (54.73)? The equivalents in PHP would be the round() function and sprintf('%01.2f', $value).
     
    norfstar, Nov 28, 2007 IP
  2. serialCoder

    serialCoder Guest

    Best Answers:
    0
    #2
    hi, this is not my own function, i just found it somewhere

    function roundNumber(rnum) {

    //var rnum = numberField.value;
    var rlength = 2; // The number of decimal places to round to
    if (rnum > 8191 && rnum < 10485) {
    rnum = rnum-5000;
    var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
    newnumber = newnumber+5000;
    } else {
    var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
    }
    return newnumber;
    }
     
    serialCoder, Nov 28, 2007 IP
    norfstar likes this.
  3. norfstar

    norfstar Peon

    Messages:
    1,154
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Works perfectly - rep added :).
     
    norfstar, Nov 28, 2007 IP