如何在 JavaScript 中使用除法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7331923/
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
How to use division in JavaScript
提问by Dayzza
I want to divide a number in JavaScript and it would return a decimal value.
我想在 JavaScript 中对一个数字进行除法,它会返回一个十进制值。
For example: 737/1070
- I want JavaScript to return 0.68
; however it keeps rounding it off and return it as 0
.
例如:737/1070
- 我希望 JavaScript 返回0.68
;但是它会不断将其四舍五入并将其返回为0
.
How do I set it to return me either two decimals place or the full results?
如何设置它以返回两位小数或完整结果?
回答by Charles Ma
Make one of those numbers a float.
将其中一个数字设为浮点数。
737/parseFloat(1070)
or a bit faster:
或者更快一点:
737*1.0/1070
convert to 2 decimal places
转换为2位小数
Math.round(737 * 100.0 / 1070) / 100
回答by KooiInc
(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))
(737/1070).toFixed(2);
将结果四舍五入到 2 位小数并将其作为字符串返回。在这种情况下,舍入结果0.69
顺便说一下,而不是0.68
。如果你需要一个真正的浮点数从你的部门四舍五入到 2 位小数,使用parseFloat((737/1070).toFixed(2))
回答by Vladimir
Also you can to use .toPrecision(n)
, where n
is the number of digits.
您也可以使用.toPrecision(n)
,其中n
是位数。
回答by Billy Moon
to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )
要将其保留到小数点后两位,您可以: alert( Math.round( 737 / 1070 * 100) / 100 )
回答by elraphty
Try this
尝试这个
let ans = 737/1070;
console.log(ans.toFixed(2));
toFixed() function will do
toFixed() 函数会做