How to use division in JavaScript

混江龙づ霸主 提交于 2019-12-05 08:21:07

问题


I want to divide a number in JavaScript and it would return a decimal value.

For example: 737/1070 - I want JavaScript to return 0.68; however it keeps rounding it off and return it as 0.

How do I set it to return me either two decimals place or the full results?


回答1:


Make one of those numbers a float.

737/parseFloat(1070)

or a bit faster:

737*1.0/1070

convert to 2 decimal places

Math.round(737 * 100.0 / 1070) / 100



回答2:


(737/1070).toFixed(2); rounds the result to 2 decimals and returns it as a string. In this case the rounded result is 0.69 by the way, not 0.68. If you need a real float rounded to 2 decimals from your division, use parseFloat((737/1070).toFixed(2))




回答3:


Also you can to use .toPrecision(n), where n is the number of digits.




回答4:


to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )




回答5:


Try this

 let ans = 737/1070;
 console.log(ans.toFixed(2));

toFixed() function will do



来源:https://stackoverflow.com/questions/7331923/how-to-use-division-in-javascript

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