Javascript always returns float numbers

只愿长相守 提交于 2019-12-13 09:12:24

问题


Thats my jquery code. And the variable "procenti" always return like 92.3076923076923 % long decimal number. I would like that number to be without the decimals, only 92%. I tried .toFixed() method but it doesnt works.

When the equation is like procenti=(3/10)*100; == 30%, the number in html looks just what i want without decimals.

for(var i=1; i<14; i++){

  var zmage=parseFloat($('#zm'+i).text());
  var odigrane=parseFloat($('#od'+i).text());
  var procenti=0;


  if(zmage == 0){
      $('#pr'+(i)).html(0 + ' %');
  }
  else{
      procenti=(zmage/odigrane)*100;
      $('#pr'+(i)).text(procenti + ' %');
  }

  }

回答1:


round() function will round off value.

Math.round(procenti);

Otherwise there are another functions ceil() & floor()




回答2:


You should use either

Math.floor() 

It returns the largest integer less than or equal to a given number.

or

Math.ceil() 

It returns the smallest integer greater than or equal to a given number.

or

Math.round()

It returns the value of a number rounded to the nearest integer.

It depends on what you actually want.




回答3:


You could do something like this:

function strip(number) {
return (parseFloat(number).toPrecision(12));

}

Hope this helps && pozdrav iz Velenja! :)



来源:https://stackoverflow.com/questions/38526389/javascript-always-returns-float-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!