Round a float up to the next integer in javascript

前端 未结 4 1979
北海茫月
北海茫月 2020-12-10 00:46

I need to round floating point numbers up to the nearest integer, even if the number after the point is less than 0.5.

For example,

  • 4.3 should be 5 (no
相关标签:
4条回答
  • 2020-12-10 01:03

    Use ceil

    var n = 4.3;
    n = Math.ceil(n);// n is 5
    
    0 讨论(0)
  • 2020-12-10 01:18

    Round up to the second (0.00) decimal point:

     var n = 35.85001;
     Math.ceil(n * 100) / 100;  // 35.86
    

    to first (0.0):

     var n = 35.800001;
     Math.ceil(n * 10) / 10;    // 35.9
    

    to integer:

     var n = 35.00001;
     Math.ceil(n);              // 36
    

    jsbin.com

    0 讨论(0)
  • 2020-12-10 01:24

    Use

    Math.ceil( floatvalue );
    

    It will round the value as desired.

    0 讨论(0)
  • 2020-12-10 01:25

    Use the Math.ceil[MDN] function

    var n = 4.3;
    alert(Math.ceil(n)); //alerts 5
    
    0 讨论(0)
提交回复
热议问题