Javascript 在javascript中将浮点数向上舍入到下一个整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11187367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:50:32  来源:igfitidea点击:

Round a float up to the next integer in javascript

javascriptfloating-pointrounding

提问by Heba Gomaah

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

我需要将浮点数四舍五入到最接近的整数,即使点后的数字小于 0.5。

For example,

例如,

  • 4.3 should be 5 (not 4)
  • 4.8 should be 5
  • 4.3 应该是 5(不是 4)
  • 4.8 应该是 5

How can I do this in JavaScript?

我怎样才能在 JavaScript 中做到这一点?

回答by Peter Olson

Use the Math.ceil[MDN]function

使用Math.ceil[MDN]功能

var n = 4.3;
alert(Math.ceil(n)); //alerts 5

回答by Nicola Peluchetti

Use ceil

ceil

var n = 4.3;
n = Math.ceil(n);// n is 5

回答by hlcs

Round up to the second (0.00) decimal point:

向上舍入到第二个 (0.00) 小数点:

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

to first (0.0):

首先(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

jsbin.com

回答by Ashwin Singh

Use

Math.ceil( floatvalue );

It will round the value as desired.

它将根据需要舍入该值。