admin管理员组文章数量:1134246
I have the following code to calculate a certain percentage:
var x = 6.5;
var total;
total = x/15*100;
// Result 43.3333333333
What I want to have as a result is the exact number 43
and if the total is 43.5
it should be rounded to 44
Is there way to do this in JavaScript?
I have the following code to calculate a certain percentage:
var x = 6.5;
var total;
total = x/15*100;
// Result 43.3333333333
What I want to have as a result is the exact number 43
and if the total is 43.5
it should be rounded to 44
Is there way to do this in JavaScript?
Share Improve this question edited Oct 29, 2014 at 19:42 John Washam 4,1034 gold badges34 silver badges46 bronze badges asked Aug 6, 2011 at 16:07 idontknowhowidontknowhow 1,5275 gold badges17 silver badges23 bronze badges5 Answers
Reset to default 187Use the Math.round()
function to round the result to the nearest integer.
//method 1
Math.ceil(); // rounds up
Math.floor(); // rounds down
Math.round(); // does method 2 in 1 call
//method 2
var number = 1.5; //float
var a = parseInt(number); // to int
number -= a; // get numbers on right of decimal
if(number < 0.5) // if less than round down
round_down();
else // round up if more than
round_up();
either one or a combination will solve your question
total = Math.round(total);
Should do it.
Use Math.round
to round the number to the nearest integer:
total = Math.round(x/15*100);
a very succinct solution for rounding a float x:
x = 0|x+0.5
or if you just want to floor your float
x = 0|x
this is a bitwise or with int 0, which drops all the values after the decimal
本文标签: operatorsHow can I round to whole numbers in JavaScriptStack Overflow
版权声明:本文标题:operators - How can I round to whole numbers in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736825304a1954463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论