[英]Javascript how to return number with x decimal places
For a given integer I want to return a number with that many decimal places.对于给定的 integer,我想返回一个小数位数那么多的数字。 For example
const decimals = 5
should return .00001
.例如
const decimals = 5
应该返回.00001
。 I tried this 10 ** (-1 * decimals)
but instead of .00001
I am getting .00000999999999999999
.我尝试了这
10 ** (-1 * decimals)
但不是.00001
我得到的是.00000999999999999999
。 What is going on here?这里发生了什么? What is the correct way to do this?
这样做的正确方法是什么?
Just use .toFixed(nN)
.只需使用
.toFixed(nN)
。
const decimals = 5; let num =.0123456789; console.log(num.toFixed(decimals));
This should work:这应该有效:
const decimals = 5; const res = (1 / 10**decimals).toFixed(decimals); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.