[英]How to convert an integer with n decimal places to a float
I have this integer我有这个整数
7839486009458047182 7839486009458047182
I have a variable that tells me this number should have n decimal places (In this case 18)我有一个变量告诉我这个数字应该有 n 个小数位(在这种情况下是 18)
How can I change it to 7.839486009458047182我怎样才能把它改成 7.839486009458047182
(If React has this as a method I could use in a template that's even better!) (如果 React 有这个方法,我可以在模板中使用,那就更好了!)
If you're not too bothered about precision, you can simply divide the integer by 10 ** decimals
, for example:如果您不太关心精度,您可以简单地将整数除以
10 ** decimals
,例如:
console.log(7839486009458047182 / (10 ** 18)); // ^ 7.839486009458047
Mind that floats have limited precision.请注意浮点数的精度有限。 If precision is key, keep it as an integer (or bigint).
如果精度是关键,请将其保留为整数(或 bigint)。 If it's just for display purposes, then a small amount of imprecision shouldn't be an issue.
如果只是为了显示目的,那么少量的不精确应该不是问题。
You can divide the integer by 10 raised to the number of decimal places.您可以将整数除以 10 到小数位数。
let integer = 7839486009458047182 function setDP(number, decimalPlaces) { return number / 10 ** decimalPlaces } console.log(setDP(integer, 18))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.